我在MVC 4项目中使用了DataAnnotations,它运行良好,包括客户端验证。
我正在启动一个MVC 5项目,但我遇到了DataAnnotations和验证问题。 MVC 4项目没有使用Bootstrap,这个新项目使用Bootstrap 3,但我怀疑这是个问题。日期未格式化,即使指定了日期,也不需要注释字段。即使notes字段为空,ModelState也显示有效。
我的观点
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.OnGoing, new
{
@class = "control-label col-md-2"
})
<div class="col-md-10">
@Html.EditorFor(model => model.OnGoing)
@Html.ValidationMessageFor(model => model.OnGoing)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Notes, new
{
@class = "control-label col-md-2"
})
<div class="col-md-10">
@*@Html.TextAreaFor(model => model.Notes, 10, 150, null)*@
@Html.EditorFor(model => model.Notes)
@Html.ValidationMessageFor(model => model.Notes)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
的web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
DataAnnotations的部分类
[MetadataType(typeof(CaseFormatting))]
public partial class MetaCase
{
}
public class CaseFormatting
{
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime CreatedDate
{
get;
set;
}
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public DateTime UpdatedDate
{
get;
set;
}
[Required(ErrorMessage="required")]
public string Notes
{
get;
set;
}
}
捆绑
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
答案 0 :(得分:2)
至于DataAnnotations不起作用,我的错误是部分类被命名为MetaCase而不是Case。
对于不起作用的验证不起作用,我引用了jqueryval js而不是我的bundle中的jquery.unobtrusive。这应该是怎么看的:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));