Unobtrusive validation doesn't work with Ajax.BeginForm

Oleksandr Fentsyk picture Oleksandr Fentsyk · Jan 19, 2012 · Viewed 40k times · Source

I have View with Model1 where I put Ajax.BeginForm() and in this View i have PartialView with Model2 where i put Ajax.BeginForm(). So only in first form working unobtrusive validation. Why only in first form working validation?

first View

@model Model1

@using (Ajax.BeginForm("Action1","Controller",null,new AjaxOption(){ onSuccess = "alert('=)')"},null)
{

   <intput type="submit" value="Save" />
}


Model2 model2 = new Model2();
@Html.EditorFor(m=>model2)

**In Model2 view i have. **

@model Model2 
@using (Ajax.BeginForm("AddStreet","Controller",new AjaxOption(){onSuccess = "alert('=)'")},option,null)
{

        @Html.LabelFor(m => Model.Name):
        @Html.TextBoxFor(m => Model.Name)
        @Html.ValidationMessageFor(m => Model.Name)

       <intput type="submit" value="Save" />
}

Thanks @Darin Dimitrov for answer.

Answer

Darin Dimitrov picture Darin Dimitrov · Jan 20, 2012

That's because the second view is loaded with AJAX at a later stage and you need to call $.validator.unobtrusive.parse(...) immediately after its contents is injected into the DOM in order to enable unobtrusive validation. Look at the following blog post for more details.

So in your case, instead of alerting in the OnSuccess callback of the first AJAX call, subscribe to a javascript function which will invoke this method:

@using (Ajax.BeginForm(
    "Action1",
    "Controller",
    null,
    new AjaxOptions { 
        OnSuccess = "onSuccess",
        UpdateTargetId = "result"
    },
    null)
)
{
    <input type="submit" value="Save" />
}

and then in your javascript file:

var onSuccess = function(result) {
    // enable unobtrusive validation for the contents
    // that was injected into the <div id="result"></div> node
    $.validator.unobtrusive.parse($(result));
};