Tutorial :jQuery Validation - adding required fields dynamically via ajax in MVC2



Question:

I'm trying to use jQuery validation on a form in MVC2. I'm using the: MicrosoftMvcJQueryValidation.js from the futures project.

When the form first loads it is for the RepresentativeViewModel and there are three fields that are validated against. The validation works perfectly for them.

A user may click on a link which loads in 3 additional required fields via an Ajax represented by the class ContactViewModel.

I've got it working so that the MVC framework sends back the right window.mvcClientValidationMetadata data to the browser and the __MVC_EnableClientValidation and __MVC_CreateValidationOptions functions are being called for the newly added fields.

However when the submit button is pressed only the first 3 fields are being validated against.

The models I'm using are:

public class RepresentativeViewModel  {      [HiddenInput(DisplayValue=false)]      public int Id { get; set; }        [Required(ErrorMessage = "Name is required")]      public string Name { get; set; }        [Required(ErrorMessage = "Telephone is required")]      public string Telephone { get; set; }        [Required(ErrorMessage = "Website is required")]      public string Website { get; set; }        public IEnumerable<ContactViewModel> ContactList { get; set; }  }    public class ContactViewModel  {      [HiddenInput(DisplayValue = false)]      public int Id { get; set; }        public int RepresentativeId { get; set; }      public RepresentativeViewModel Representative { get; set; }        [Required(ErrorMessage="First Name is required")]      public string FirstName { get; set; }        [Required(ErrorMessage = "Last Name is required")]      public string LastName { get; set; }        [Required(ErrorMessage = "Job is required")]      public string JobTitle { get; set; }  }  

Through a bit of debugging I found this in jquery.validate:

// check if a validator for this form was already created  var validator = $.data(this[0], 'validator');  if ( validator ) {      return validator;  }  

it seems that after I load the extra fields in via ajax, the validator associated with the form will never be updated. If I comment out the line:

    return validator;  

then only the new fields get validated.

How do I get both the original and the new fields to be validated when the user clicks on submit?


Solution:1

Try calling

      $(document).ajaxComplete(function (event, request, settings) {          $.validator.unobtrusive.parse(document);      });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »