Enable client validation in Razor views (ASP MVC 3

2019-01-23 22:31发布

问题:

I try to add client side validation using this line of code:

@Html.EnableClientValidation()

But I keep getting this error message:

Compiler Error Message: CS1502: The best overloaded method match for 'Microsoft.WebPages.WebPageUltimateBase.Write(Microsoft.WebPages.Helpers.HelperResult)' has some invalid arguments

Is this working for anyone else, or is it another approach for this in ASP MVC 3?

回答1:

You can, instead, use the following in place of the expected line of code.

@(ViewContext.ClientValidationEnabled = true)

Probably an oversight in the extension methods for htmlhelper.

Actually, you can use the HtmlHelper method by doing the following

@{ Html.EnableClientValidation(); }


回答2:

Hey, in ASP.NET MVC3, there's no need to add Html.EnableClientValidation() in view page, instead, just enable the clientValidation in the webconfig file as below:

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


回答3:

this tag

     @{ Html.EnableClientValidation(false); }

must come before the

  @using (Html.BeginForm())


回答4:

Are you using the html <form> element on your page instead of Html.BeginFormto create your html FORM.

I had this exact same problem and worked out it was because the i was not using Html.BeginForm to create my FORM resulting in the required input attributes data-val-required="The Email field is required." data-val="true" class="input-validation-error and the place holder for the validation was not being injected into the page even though i had the @Html.ValidationMessageFor(m => m.User.Role) inserted on my view page.



回答5:

In my case, I was not using EditorFor, but TextBoxFor!

Make sure you use:

             <td>@Html.EditorFor(m => m.Email)</td>