0

I have AJAX Form in MVC 3.

In Index view:

<div id="ajaxcontactform">
      <% Html.RenderPartial("ContactForm", Model); %>
</div>

AJAX form on ContactForm Partial View

<% using (Ajax.BeginForm("Contact", new AjaxOptions()
{
   UpdateTargetId = "ajaxcontactform",
   OnBegin = "ShowProcessing",
   OnComplete = "HideProessing",
   InsertionMode = InsertionMode.Replace
}))
{%>
<%: Html.ValidationSummary()%>
<%: Html.TextBoxFor(m => m.Name, new { Class = "contacttextform" })%>
<%}%>

My controller:

 [HttpPost]
    public ActionResult Contact(ContactForm form)
    {
        if (Request.IsAjaxRequest())
        {
             // on error
            if (!ModelState.IsValid)
                return PartialView("ContactForm", form);

           // TODO: My data processing code here  

           // return partial view on success
             return PartialView("ContactForm", new ContactFormModel());   
         }
   }

my client side custom validation JavaScript code: I just referenced this file in master page. This code runs once when DOM get loaded/created once.

    $.validator.addMethod("phonenumber", function (value, element, params) {

    if (!value)
        return true;
    var regex = /^[\s\d\+\(\)]+$/;
    return regex.test(value);
   });
   jQuery.validator.unobtrusive.adapters.addBool("phonenumber");

My client side validation works fine when I first load my page. However, once i submit my form successfully and try to submit my form again . My client side validation doesn't work and my form validate it server side.

I want to bind my client side validation again after adding new element or re-render my partial view.

Also, how should I clear my form values once it submitted successfully.

Thanks,

jNet
  • 153
  • 1
  • 1
  • 11

1 Answers1

1

You could subscribe to the OnSuccess method in the AjaxOptions and reattach the client side validation of the newly added elements using the $.validator.unobtrusive.parse method:

function OnSuccess(result) {
    $('form').removeData('validator');
    $('form').removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse('form');
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks Darin. client side validation works after re-rendering the partial view. cheers – jNet Nov 02 '12 at 10:07