I have a MVC view with a model, where, when I select something from a drop down list, it does a JSON query to my controller, gets an updated list of items for a second drop down, and repopulates the 2nd drop down with new values. I do this, but building the <option value="5">Test</option><option value="13">Another</option>.... string, and then set the HTML of the 2nd drop down with that new code:
Javascript:
$(".cmbSubCategory").html(result.SubCategoryString);
Visually, this is working well. My UI updates nicely.
However, when I save, it seems it doesn't recognise the selected value of the second drop down, which is the one I built.
Once I rebuild a control, that was originally setup by a view model:
@Html.DropDownListFor(x => x.SubCategoryId, Model.SubCategories, new { @class = "cmbSubCategory form-control" })
.. can I no longer use the selected value in the model, when I do the 'post' back to my controller?
I notice that even after visually, the 2nd dropdown is populated with a few options, when I 'View Page Source', it just shows:
<select class="cmbSubCategory form-control" data-val="true" data-val-number="The field SubCategoryId must be a number." data-val-required="The SubCategoryId field is required." id="SubCategoryId" name="SubCategoryId"><option value="0">Select a Category</option>
</select>
No options.. But in the browser, it shows items...
Edit: Found the issue!
Althought I was populating the HTML and setting the 'Selected' value in the HTML, I wasn't setting the 'val' of the drop down list!
This now works:
if (result.Success == 'true') {
if (result.SubCategoryString != "") {
$('#cmbType').val(result.TransactionTypeId);
$('#cmbCategory').val(result.CategoryId);
$(".cmbSubCategory").html(result.SubCategoryString);
$(".cmbSubCategory").val(result.SubCategoryId);
}
}
The last line is the key! $(".cmbSubCategory").val(result.SubCategoryId);
I thought building the HTML Selected option would have been enough - but you must also set the 'val' of the combo.