当我提交表单时,客户端验证工作正常,但它没有显示无效表单字段的错误消息...
模特
public class Blog : MainDbContext
{
public int Id { get; set; }
[Display(Name="Author")]
public int Profile { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Title is required.")]
public string Title { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "At least one Tag is required.")]
public string Tags { get; set; }
}
ViewModel
public class BlogEditViewModel
{
public BlogEditViewModel(Blog blogItem, IEnumerable<SelectListItem> staffList)
{
this.BlogItem = blogItem;
this.StaffList = staffList;
}
public Blog BlogItem { get; set; }
public IEnumerable<SelectListItem> StaffList { get; private set; }
}
视图
<section>
@Html.LabelFor(model => model.BlogItem.Tags)
@Html.EditorFor(model => Model.BlogItem.Tags, null, "Tags")
@Html.ValidationMessageFor(model => model.BlogItem.Tags)
</Section>
布局
<script src="/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
输出(提交表格)
<input type="text" value="ok" name="Tags" id="Tags" data-val-required="At least one Tag is required." data-val="true" class="text-box single-line input-validation-error">
<span data-valmsg-replace="true" data-valmsg-for="BlogItem.Tags" class="field-validation-valid"></span>
我期望上面的Span标记包含模型中定义的错误消息。
我怀疑的问题与EditorFor中的命名有关,因为你可以看到我使用重载来指定'htmlfieldname',因为没有这个,表单数据无法将表单字段映射到模型&amp;无法保存提交的数据。
如果我不使用重载的EditorFor,验证工作,但如上所述,表单数据无法将表单字段映射到模型
如何让验证工作?
由于 KB
答案 0 :(得分:1)
在View中添加此脚本,客户端验证工作正常,
<script src="@Url.Content("~/Script/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Script/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
我认为问题是您必须删除null, "Tags"
@Html.EditorFor(model => Model.BlogItem.Tags)
或者您必须将null, "Tags"
分配给
@Html.ValidationMessage("Tags")
例如:
查看强>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { Name="asd"})
@Html.ValidationMessage("asd")
<强>模型强>
public class RegisterModel
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}