What I'm doing: I have 3 combo boxes. The selection in the first 2 boxes determines the list in the 3rd box. Whenever a selection is made in either of the first 2 boxes, I run some jQuery that makes an $.ajax call to get the list for the 3rd box. The 3rd box is my "Item Description" box.
The problem: The jquery ajax call works. When I pick the values in the first 2 boxes, the Item Descriptions are loaded into the 3rd box. However, when I try to submit the form, the ModelState.IsValid = false and the ModelState error message says, "Item Description is required."
This is from the meta data for my model:
[Required(ErrorMessage = "Item Description is required.")]
public int ItemDescriptionID { get; set; }
I don't want the user to be able to submit the form without selecting a description. I could just validate after submission, but I was hoping MVC would do the validation.
Here's the JavaScript I am using...
function getModels() {
catId = $('#ItemModel_ItemCategoryID').val();
manuId = $('#ItemModel_ItemManufacturerID').val();
// remove all of the current options from the list
$('#ItemDescriptionID').empty();
// send request for model list based on category and manufacturer
var jqxhr = $.ajax({
url: '/Threshold/GetModels',
type: 'POST',
data: '{ CategoryID: ' + catId.toString() + ', ManufacturerID: ' + manuId.toString() + ' }',
contentType: 'application/json',
dataType: 'json',
cache: false,
async: true
});
// received list of models...
jqxhr.done(function (data) {
if (data == null) return;
try {
var ddl = $('#ItemDescriptionID');
// add each item to DDL
$.each(data, function (index, value) {
ddl.append($('<option/>', {value: data[index].ItemDescriptionID}).html(data[index].ItemDescription))
});
}
catch (result) {
alert("Done, but with errors! " + result.responseText);
}
});
// failed to retrieve data
jqxhr.error(function (result) {
alert("Error! Failed to retrieve models! " + result.responseText);
});
}
So what am I doing wrong? The form will submit if I remove the Required metadata tag. Also, after the form submits, I am able to grab the ID from the dropdown and everything works. The problem is with the modelstate/validation somehow.
EDIT:
This is my Razor for the description box...
@Html.DropDownListFor(m => m.ItemDescriptionID, new SelectList(new List<SelectListItem>()) )
@Html.ValidationMessageFor(m => m.ItemDescriptionID)