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.
You need to add those 2 files in you Partial View even if it is already in the Shared/_Layout.cshtml:
Or place this in your Partial:
You have to add a reference to
jquery.unobtrusive-ajax.js
to enable the validation withinAjax Form
Something like this:
The answer of Darin Dimitrov only works when
validate()
of thejquery validate plugin
has not been called until the Ajax success handler is called. I can't think of a scenario where this could be the case, thus i wonder why the answer was accepted as correct.Perhaps a change in the jquery validate code in the past now cause the following issue:
The issue is that
validate()
executes the following line firstwhich means that the validator object is returned when validate() is called without and further handling of the options passed.
This also means that a later call to
$.validator.unobtrusive.parse(...)
or$.validator.unobtrusive.parseElement(...)
which executes ato update the options of the validator has no effect because the options are not processed at all.
The solution here is to update the validator manually like
Revalidating the form (e.g. clicking submit) should now result in the expected results.
Here is a full example witch also includes code from the already accepted answer:
Razor
Javascript
--
As a side note, manually updating the validator is also possible by using the
rules()
method likeas this directly updates the rules of the validator without the unobtrusive stuff. But then the data-val attributes are rendered useless.
This solution worked best for me.
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:and then in your javascript file: