Reputation: 9042
In MVC 3.0 and where and when I disabled unobtrusive javascript :
<key="UnobtrusiveJavaScriptEnabled" value="false" />
If I load a form through jQuery ajax, the validation does not work! Indeed the following code returns null :
alert(Sys.Mvc.FormContext.getValidationForForm($(this).closest('form')[0]));
I know the solution when unobtrusive is enabled (through calling $.validator.unobtrusive.parse(id); ) but when it is disabled what should I do??
Upvotes: 1
Views: 1814
Reputation: 1039298
Make sure that you have called Sys.Mvc.FormContext._Application_Load();
as well.
Let's take an example.
View model:
public class MyViewModel
{
[Required]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return PartialView(new MyViewModel());
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
return Content("thanks for submitting");
}
}
View (Index.cshtml
):
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script>
<script type="text/javascript">
$.get('@Url.Action("create")', function (result) {
$('#foo').html(result);
// That's the important bit that you were probably missing
Sys.Mvc.FormContext._Application_Load();
$('form').submit(function () {
if (Sys.Mvc.FormContext.getValidationForForm(this).validate('submit').length > 0) {
return false;
}
});
});
</script>
<div id="foo"></div>
Partial containing the form that is dynamically loaded (Create.cshtml
):
@model MyViewModel
@{Html.EnableClientValidation(true);}
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Foo)
@Html.EditorFor(x => x.Foo)
@Html.ValidationMessageFor(x => x.Foo)
<button type="submit">OK</button>
}
Remark: obviously this answer is valid only if you want to use the totally obsolete Microsoft*.js
scripts instead of the recommended jQuery unobtrusive and jQuery validate plugins. So it is valid only if you set <add key="UnobtrusiveJavaScriptEnabled" value="false"/>
in your web.config.
Upvotes: 1
Reputation: 5458
I don't know why you would want to turn off validation only to do it by hand. Anyway, your problem is that when you turn off unobtrusive validation the asp.net helpers don't output the data- attributes that are used by the validation functions.
My suggestion would be to leave <key="UnobtrusiveJavaScriptEnabled" value="false" />
and un-register the jQuery events.
Upvotes: 0