我正在尝试按照Brad Wilson's recipe在我的ASP.NET MVC 3项目中集成不显眼的客户端验证。但是,它不会在渲染视图中启用。例如,我的<input>
元素(即编辑器字段)未按规定收到data-val
属性。
我已完成以下操作以启用不显眼的客户端验证:
Web.config
:
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
</configuration>
Options.cs
:
public class Options
{
// Annotate with validation rules, in order to generate client-side validation code
[Required, StringLength(60)]
public string Bugs = "";
}
_Layout.cshtml
:
<head>
<script src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
</head>
Options.cshtml
:
@model MyProject.Models.Options
<div id="options-form">
@Html.ValidationSummary(true)
<fieldset>
<legend>Options</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Bugs)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Bugs)
@Html.ValidationMessageFor(model => model.Bugs)
</div>
</fieldset>
</div>
为编辑器字段生成此HTML:
<div class="editor-label">
<label for="Bugs">Bugs</label>
</div>
<div class="editor-field">
<input class="text-box single-line" id="Bugs" name="Bugs" type="text" value="" />
如您所见,没有data-val
属性:(
答案 0 :(得分:3)
您忘记使用form
。使用Html.BeginForm
<div id="options-form">
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Options</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Bugs)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Bugs)
@Html.ValidationMessageFor(model => model.Bugs)
</div>
</fieldset>
}
</div>
这将初始化FormContext
,您的输入将接收data-val- *验证属性