3

我试图在我的ASP.NET MVC 3项目中集成不显眼的客户端验证,按照Brad Wilson's recipe。但是,它在渲染视图中未启用。例如,我的<input>元素(即编辑器字段)未按规定收到data-val属性。为什么ASP.NET MVC 3在这种情况下不支持客户端验证?

我做了以下,以使不显眼的客户端验证:

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属性:(

回答

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,你的投入将收到的数据val- *属性验证

+0

看来我不得不专门使用Html.BeginForm(),刚刚进入一个

标签自己有没有效果。谢谢! – aknuds1

+2

如果您使用手动表单标记,则还必须手动初始化FormContext。 @ { ViewContext.FormContext = new FormContext(); } – archil