我有一个带有 DropDownList 控件和文本框的部分视图。
当未选择任何内容或未输入文本时,ModelState.IsValid 为 FALSE
但是我看不到在我的属性上显示的任何验证错误。
这是为什么?我可以在 ModelState.Value.Errors 属性中看到“名称是
缺失”例如。
当我确认无效视图时,我在输出窗口中看到:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll
public ActionResult Edit()
{
return LoadEditTemplates();
}
[HttpPost]
public ActionResult Update(EditTemplateListViewModel viewModel)
{
if (ModelState.IsValid && !_templateDataProvider.TemplateExists(viewModel.Name))
{
Template template = Mapper.Map<EditTemplateListViewModel, Template>(viewModel);
_templateDataProvider.UpdateTemplate(template);
return new JsonNetResult(new { success = true });
}
return PartialView(viewModel);
}
private ActionResult LoadEditTemplates()
{
var templates = _templateDataProvider.GetTemplates();
EditTemplateListViewModel editTemplateViewModel = new EditTemplateListViewModel()
{
DisplayList = Mapper.Map<IEnumerable<Template>, IEnumerable<TemplateViewModel>>(templates),
};
return PartialView(editTemplateViewModel);
}
public class EditTemplateListViewModel
{
[Required(ErrorMessage = "No template selected.")]
public int TemplateId { get; set; }
[Required(ErrorMessage="Name is missing")]
public string Name { get; set; }
public IEnumerable<TemplateViewModel> DisplayList { get; set; }
}
@model ITMS.Web.Models.EditTemplateListViewModel
@*Remote Validation*@
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Update", "Template"))
{
@Html.ValidationSummary(false)
@Html.DropDownListFor(x => x.TemplateId, new SelectList(Model.DisplayList, "TemplateId", "Name"), new { @class = "listviewmodel" })
<p class="editor-label">@Html.LabelFor(model => model.Name)</p>
<p class="editor-field">@Html.EditorFor(model => model.Name)</p>
<p class="editor-field">@Html.ValidationMessageFor(model => model.Name)</p>
}