3
votes

I'm trying to integrate unobtrusive client-side validation in my ASP.NET MVC 3 project, as per Brad Wilson's recipe. However, it does not get enabled in the rendered view. For example, my <input> elements (i.e., editor fields) do not receive a data-val attribute as prescribed.

I have done the following to enable unobtrusive client-side validation:

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>

This HTML gets generated for the editor field:

<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="" />

As you can see, no data-val attribute :(

1

1 Answers

3
votes

You forgot to use form. Surround your fieldset with 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>

This will initialize FormContext and your inputs will receive data-val-* validation attributes