Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

javascript - MVC3 Client side validation not working

I'm using MVC3 with Razor.
I've included the following in my _Layout.cshtml:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>  

My form looks like:

  @{
       ViewBag.Title = "Register"; 
       Html.EnableClientValidation();
   }  
   @using (Html.BeginForm("Register"))
   {
      <fieldset>
        <p>
            @Html.LabelFor(o => o.Email)
            @Html.TextBoxFor(o => o.Email)
            @Html.ValidationMessageFor(o => o.Email)
        </p>
  ...
 </fieldset>
}

My ViewModel has DataAnnotations (and implements IValidatableObject), and it validates during controller action. However I cannot seem to be able to use JS validation on the clientside without posting the form.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In ASP.NET MVC 3 the jquery validation plugin is the default for performing client-side validation. So you could remove all Microsoft*.js scripts from your project. You only need the following:

<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

and remove the Html.EnableClientValidation(); call. Client validation is enabled in web.config:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...