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.
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));
};
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>
This solution worked best for me.
$.validator.unobtrusive.parse(document);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With