【发布时间】:2013-11-01 14:23:35
【问题描述】:
我在做什么:我有 3 个组合框。前 2 个框中的选择决定了第 3 个框中的列表。每当在前 2 个框中的任何一个中进行选择时,我都会运行一些 jQuery 进行 $.ajax 调用以获取第 3 个框的列表。第三个框是我的“项目描述”框。
问题: jquery ajax 调用有效。当我选择前 2 个框中的值时,项目描述被加载到第 3 个框中。但是,当我尝试提交表单时,ModelState.IsValid = false 并且 ModelState 错误消息显示“需要项目描述”。
这是来自我的模型的元数据:
[Required(ErrorMessage = "Item Description is required.")]
public int ItemDescriptionID { get; set; }
我不希望用户在不选择描述的情况下提交表单。我可以在提交后进行验证,但我希望 MVC 会进行验证。
这是我正在使用的 JavaScript...
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);
});
}
那我做错了什么?如果我删除必需的元数据标签,表单将提交。此外,表单提交后,我可以从下拉列表中获取 ID,一切正常。问题出在模型状态/验证上。
编辑:
这是我的描述框剃刀...
@Html.DropDownListFor(m => m.ItemDescriptionID, new SelectList(new List<SelectListItem>()) )
@Html.ValidationMessageFor(m => m.ItemDescriptionID)
【问题讨论】:
-
当你说“当我选择前2个框中的值时,项目描述被加载到第3个框中”是填充后用户选择的描述框吗?或者在填充描述选项框后直接点击提交而不选择任何值?
-
描述框在用户点击提交前被用户选中。如果描述框中没有选择任何内容,我不希望用户提交。
标签: c# javascript jquery ajax asp.net-mvc-4