为什么ASP.NET MVC 3在这种情况下不启用客户端验证?

时间:2011-09-01 11:52:33

标签: asp.net-mvc asp.net-mvc-3 unobtrusive-javascript unobtrusive-validation

我正在尝试按照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属性:(

1 个答案:

答案 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- *验证属性