Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Sunday, October 23, 2011

ASP.Net MVC Client Validation For Dynamically Added Form

This is how I have implemented the client side validation with MVC3 client side validation with JQuery validation plugin. The requirement was to create a model dialog with a form which is loaded via an Ajax request to the server.

  1. Enable client validation in web.config
We need to enable client side validation in web.config application settings section like thism


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


    2 The form
 In your form you need to have a FormContext otherwise it will not generate validation attributes.  If the FormContext is null we need to create a new FormContext  like this in your view.
 
@{using (Html.BeginForm("Create", "Person", FormMethod.Post)
  {
      if (this.ViewContext.FormContext == null)
      {
          this.ViewContext.FormContext = new FormContext();
      }
    // .....
  }


    3 Phrase validation attributes 
 Then after the ajax request we need to phrase validation attributes using JQuery like this,<br />
 
$.get("@Url.Action("Create", "Person")", null, function (data) {
         $('#yourDivId').html(data);
         $("form").removeData("validator");
         $("form").removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse("form");          
   });