Value from JQuery populated field not binding to MVC model - javascript

I'm working on a project with ASP.NET MVC, using Razor. Once the form finishes loading on the page, I expect the user triggers .on ('change') in an input. Once this happens, an AJAX call is executed, returning the user's data, disabling and filling the inputs that are linked to the properties of a model that starts empty (when the page is loaded).
The data is filling up without problems, but when I send it back to the controller to be processed, the values that correspond to the inputs that were filled after the AJAX execution arrive as null.
<div class="form-label-group col-md-4 mb-3">
#Html.LabelFor(model => model.AttendeeName, new { #class = "upside-label", #for = "firstName" })
#Html.EditorFor(model => model.AttendeeName, new { htmlAttributes = new { #class = "form-control", #id = "firstName", #placeholder = Resources.ResourcesPerson.PlaceholderPersonName } })
#Html.LabelFor(model => model.AttendeeName, new { #class = "downside-label", #for = "firstName" })
<div class="text-danger">
#Html.ValidationMessageFor(model => model.AttendeeName)
</div>
</div>
I have tried the following without success:
$("input[name=AttendeeName]").attr('disabled', true);
$("input[name=AttendeeName]").val(data.AttendeeName).change()
Thank you for your assistance.

This is expected behaviour. disabled elements are not sent in form data.
If you still want those values to be sent, don't disable the fields. Possibly try readonly instead, assuming that you don't want users to edit the fields:
$('input[name="AttendeeName"]').prop('readonly', true);

Related

Combo Box selected value to javascript

In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?
Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});

How to show dropdown list in the #Html.EditorFor() when user clicks on the text input box

I am passing data from the Controller to the View using the ViewData
Code in the controller:
public ActionResult Create()
{
ViewData["gN"] = new SelectList(db.gT, "id", "gN");
return View();
}
In the View I am using #Html.EditorFor() to create the new item for our table which we store in the database.
<div class="col-md-10">
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.groupid, "", new { #class = "text-danger" })
</div>
When I am using #Html.DropDownList our list of gN is perfectly showing as the dropdown list
#Html.DropDownList("gN", null, htmlAttributes: new { #class = "form-control" })
I want to use EditorFor() so that when the user starts typing in the input box, the dropdown list appears below it. and if that text which user is typing, present in the dropdown then the user can select it.
How we should show the list gN (which we are getting using ViewData from Controller) in the EditorFor() HTML element?
The Html.EditorFor() method always creates an <input> element, though the type attribute can vary depending on the model property type. HTML5 actually supports exactly what you want with the <datalist> element, which you tie to an <input> element with the list attribute. the <datalist> element takes child <option> elements containing the values you want in the list.
Making some guesses about your models here...
// Controller
public ActionResult Create()
{
ViewData["gN"] = db.gT;
return View();
}
// View
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control", list="gN-datalist" } })
<datalist id="gn-datalist">
#foreach (var item in (gT)ViewData["gN"])
{
<option value="#item.id">#item.gN</option>
}
</datalist>
You could also create an HtmlHelper extension method that would create this for you.

MVC #Html.DropDownListFor change displayed value in javascript

Using MVC 4, I am trying to change the displayed value in the view for #Html.DropDownListFor, based on the action of another drop down list. In the below example, when the user selects any value in the state list, I want the #Html.DropDownListFor to display the indexed 203 value which is US. How to do this?
//in the controller
ViewBag.statelist = new SelectList(db.states, "state_abbr", "state_name");
ViewBag.countrylist = new SelectList(db.countries, "country_id", "country_name", -1);
//in the View
<div class="form-group">
#Html.LabelFor(model => model.states)
#Html.DropDownList("ddlstate", ViewBag.statelist as SelectList, Model.rrq_sec1_waddr_stprov, htmlAttributes: new { #onchange="StateChange()" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.country)
#Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { #id="ddlcountry" })
</div>
//javascript
function StateChange() {
var state = document.getElementById("ddlstate").value;
$("#ddlcountry").val = 203;
};
How do I get the #ddlcountry index=203 which is "US" show up in view then the state drop down changes?
This might help u to select value in second dropdown, onchange event of first dropdown using this jQuery function.
$('#ddlstate').change(function () {
$("#ddlcountry").val( $('#ddlstate').val());
});

mvc dropdownlistfor validation run before submitting

I have an MVC 5 Application. I have a View that inherits from a Model View. I have a DropDownlistFor with Validation that cannot be empty.
The problem I have is that Validation executes as soon as I select an item from Dropdownlist. When I select the same First item "Choose a Country", I mean, y select the same default option, validation execute and show a Message "Country is required"...
I put an alert on jquery Submit button and on Controller Method and it does not reach that point.
Another curious thing is that this App is a Migration from Entity Framework to Enterprise Library Store Procedure ..
The Model that inherits the View is loaded on the Controller from Store Procedure instead of EntityFrawork.
This should be transparent to the View. But this error happens only in this versiĆ³n. It Works fine with Entity Framework.
Here is part of the code..
#model AvivaVozSP.Models.UserViewModel
#using System.Web.Mvc.Ajax
<form action="#Url.Action("Create", "Users")" id="form" enctype="multipart/form-data" method="post">
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries, new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
<div class="DvCampoUp">
#Html.ValidationMessageFor(model => model.user.Country_id, "", new { #class = "text-danger" })
</div>
</form>
<script language="javascript" type="text/javascript">
$('form').submit(function (event) {
alert(1);
});
Any Ideas?
Use the default value like this
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries,"Choose a Country", new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
and remove Choose a Country from the list

How to get the value of an EditorFor JavaScript ASP

I want to get the value of an EditorFor in ASP but it returns me nothing.
Thank you for your helps
<div class="form-group" id="ParticipantNumber">
#Html.LabelFor(model => model.ParticipantNumber, new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.ParticipantNumber)
</div>
</div>
My JavaScript code
$('#ParticipantNumber').keyup(function () {
var s = $('#ParticipantNumber').val();
console.log(s)
}
Your JavaScript is looking for $('#ParticipantNumber'), which is the element with the ID ParticipantNumber. Your code defines the editor with:
#Html.EditorFor(model => model.ParticipantNumber, new {
#class = "ParticipantNumber", disabled = "disabled" })
The intention here is to assign the input with the class ParticipantNumber, which would have meant you could address it with `$('.ParticipantNumber') instead.
However, the parameter you're using is additionalViewData; the EditorFor HTML editor does not have a property to reflect HTML properties back into the renderer. Your two options are:
Write a custom template
Change the way you're referencing the input
Option 1 is possibly a bit over-the-top for your needs; with option 2, the following will solve your problem, by simply referencing the input within your <div id='ParticipantNumber'>:
#Html.EditorFor(model => model.ParticipantNumber)
$('#ParticipantNumber input').keyup(function () {
var s = $(this).val();
console.log(s)
}
I'm a bit late coming to this party but I recently had this issue with Html.EditorFor.
What fixed it for me was to simply switch to TextBoxFor. So instead of:
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
Change it to:
#Html.TextBoxFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
In the javascript, you are querying for the "id" attribute, but #Html.EditorFor does not emit any id by default. You can modify your code like this
#Html.EditorFor(model => model.ParticipantNumber, new { #class = "ParticipantNumber", disabled = "disabled", id="ParticipantNumber" })
Then your javascript will work.

Categories

Resources