我有一个简单的 MVC 网站,它显示一个用于编辑目的的 jquery 对话框。在此对话框中是一个文本区域,它接受用户可以输入的以逗号分隔的技能列表。提交后,我的模型绑定器将其转换为List。这是我的模型活页夹的代码
public class EditSkillsModelBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var form = controllerContext.HttpContext.Request.Form;
var skillsAsString = form["SkillsAsString"];
var user = bindingContext.Model as UserEditDetailsModel;
//FOR VALIDATION
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState {Value = valueResult};
if (string.IsNullOrEmpty(skillsAsString))
{
bindingContext.ModelState.AddModelError("Skills", "You must enter at least one skill.");
}
else
{
user.Skills = string.IsNullOrEmpty(skillsAsString) ? new List<string>() : skillsAsString.Split(',').Select(i => i.Trim()).ToList();
}
}
}
这是我的部分视图的代码
@using (Ajax.BeginForm("EditUserDetails", new { }, new AjaxOptions { }, new { id = "EditUserDetailsForm" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>UserEditDetailsModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Skills)
</div>
<div class="editor-field">
@Html.TextArea("SkillsAsString", Model.Skills.ToCommaSeparatedString())
@Html.ValidationMessageFor(model => model.Skills)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
@*Enable Client Side Validation*@
<script type="text/javascript">
$(document).ready(function () {
$.validator.unobtrusive.parse("#content_container > form");
});
</script>
我所有的简单验证(例如 [Required])都在客户端工作。模型绑定器验证也有效,但是没有显示错误消息。我假设我在 javascript 中遗漏了一些东西来注册错误,但我不知道它是什么。任何帮助,将不胜感激。谢谢。
这是问题的屏幕截图