I'm developing an MVC 5 application. Within a Razor View there are two drop down lists. When a value is selected from the first one (productID), a JQuery and Ajax call is made to return Json Data which populates the second drop down list (additionalID).
Drop Downs
@Html.DropDownListFor(m => m.productID, Model.ProductList, "Select", new { @class = "form-control" })
@Html.DropDownListFor(m => m.additionalID, Enumerable.Empty<SelectListItem>(), "Select", new { @class = "form-control" })
JQuery
$("#productID").change(ProductChange);
function ProductChange() {
var val = $("#productID").val();
var valText = $("#productID option:selected").text();
if (val == 22 || val == 25 || val == 29 || val == 20)
{
$('#AdditionalProducts').show('fast');
$('label[for="additionalID"]').html('Please select a ' + valText + ' option');
var dataPost = { productID: val };
$.ajax({
type: "POST",
url: '/Proposal/GetAdditionalProducts/',
async: false, //This makes the JQuery below wait until $.ajax() call is finished
data: dataPost,
dataType: "json",
error: function () {
alert("An error occurred." + val);
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#additionalID").html(items);
}
});
}
else
{
$('#additionalID').empty(); // clear drop down list
$('#AdditionalProducts').hide('fast');
}
}
When editing a record, within the MVC Controller Edit Action I pass values for both productID and additionalID to the Razor View. Both drop downs appear, and the selected value for productID is set, however, the selected value for additionalID is not set.
Can anyone please help me with how to set the value of the second down drop list?
Thanks in advance.