Why HtmlHelper would skip validation attributes

2019-08-30 10:25发布

问题:

Why @Html.TextBoxFor and other helpers would skip jquery.validation attributes and create elements without those? Am I missing some references or something? It's MVC 3.0 project.

If I add them manually like that:

@Html.TextBoxFor(x => x.Name, 
       new { data_val="true", data_val_required="Need that field" })

then unobtrusive validation works. But it's suppose build elements and put those attributes based on Model's DataAnnotations. Model is there, textbox inside of a form body, and still doesn't work. What could it be?

upd: UnobtrusiveJavaScriptEnabled set to true in web.config

回答1:

Please ensure these two lines in your web.config file

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>


回答2:

For unobtrusive validation to work you need to ensure that UnobtrusiveJavaScriptEnabled is set to true in your Web.config and that you have included these 3 scripts:

  • jQuery (~/Scripts/jquery-1.8.2.js)
  • jQuery Validate (~/Scripts/jquery.validate.js)
  • the MVC plugin for unobtrusive client validation with jQuery Validate (~/Scripts/jquery.validate.unobtrusive.js).


回答3:

1.if the text box is loading via ajax, it's may not be parsed for Unobtrusive validation. 2.check rendered html if there is a data-val-required attribute for the text box to determine if it's a server side or client side problem.