Reputation: 1091
How do I properly make my dropdown have the correct information from the model when I'm doing an MVC Edit? My edit is using a dynamic dropdown populated by a jquery $.ajax call.
Here's my dropdown on my view...
@Html.DropDownListFor(m => m.SubdivisionID, new SelectList(new List<SelectListItem>(),
"SubdivisionID", "SubdivisionName", Model.SubdivisionID))
I make an $.ajax call and the drop down fills up with all of the options after the $.ajax call runs, but the dropdown just selects the first one in the list. How do I get the dropdown to update with the model information?
For example, the dropdown can have a selection of Item1 or Item2. The model has "Item2" saved as SubdivisionID, however, after the $.ajax call, the dropdown has "Item1" in the list because Item1 is the first item in the list.
What should I do to make the dropdown select the correct item on an Edit?
This is my JavaScript for the $.ajax call...
function getSubdivisions() {
custId = $('#CustomerID').val();
// remove all of the current options from the list
$('#SubdivisionID').empty();
// send request for list of subdivisions
var jqxhr = $.ajax({
url: '/Schedule/getSubdivisions',
type: 'POST',
data: '{ customerId: ' + custId.toString() + ' }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
cache: false,
async: true
});
// received list of models...
jqxhr.done(function (data) {
if (data == null) return;
try {
var ddl = $('#SubdivisionID');
// add each item to DDL
$.each(data, function (index, value) {
ddl.append($('<option></option>', { value: data[index].SubdivisionID }).html(data[index].SubdivisionName))
});
}
catch (ex) {
alert("Done, but with errors!\n" + ex.message);
}
});
// failed to retrieve data
jqxhr.error(function (result, errorText, thrownError) {
alert("Error! Failed to retrieve models! " + errorText + "\n" + thrownError);
});
}
UPDATE 1: I changed my DropDown Razor code, and it still does not work (see above). MVC never selects the correct list item. I'd rather have MVC handle the item selection versus me having to select the selected item from JavaScript. My JavaScript is in a separate file and presently I have not been passing any parameters.
UPDATE 2: I added the following JavaScript to my view and I updated my JavaScript to include Matt's answer.
<script type="text/javascript">
var js_doEdit = true;
var subdivisionId = @Model.SubdivisionID
</script>
Upvotes: 1
Views: 693
Reputation: 251
2 Ways to solve this:
1.
$("#YourDropDownList").val(@Model.SubdivisionID);
2.
@Html.DropDownListFor(m => m.SubdivisionID, new SelectList(new List<SelectListItem>()),"SubdivisionID","Text")
It'll auto-match your datavalue with "SubdivisionID".
Upvotes: 0
Reputation: 6423
you should be able to set the selected item in the dropdown after recreating it like this
$('#SubdivisionID').val('@Model.SubdivisionID');
you may need to add a select to the selector like this
$('#SubdivisionID select').val('@Model.SubdivisionID');
Hope this helps
Upvotes: 1