Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unobtrusive validation doesn't work with Ajax.BeginForm

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.

like image 458
Oleksandr Fentsyk Avatar asked Jan 19 '12 14:01

Oleksandr Fentsyk


3 Answers

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));
};
like image 111
Darin Dimitrov Avatar answered Nov 09 '22 10:11

Darin Dimitrov


You need to add those 2 files in you Partial View even if it is already in the Shared/_Layout.cshtml:

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

Or place this in your Partial:

<script type="text/javascript" language=javascript>
    $.validator.unobtrusive.parse(document);
</script>
like image 29
dperez Avatar answered Nov 09 '22 10:11

dperez


This solution worked best for me.

$.validator.unobtrusive.parse(document);
like image 3
JeremyFromNaples Avatar answered Nov 09 '22 09:11

JeremyFromNaples