The application i am working is a single page application using asp.net MVC 4, so i am using ajax for loading the partial views.
jquery.validate.js and jquery.validate.unobtrusive.js has been added in _layout.cshtml using bundling. These were not added in partial views.
After loading the partial views through ajax, the elements were attached to some container. Now the validation is not working for the attached form and i know the reason. JQuery Unobtrusive parses the document at the initial loading of page.
And as many sites saying to add $.validator.unobtrusive.parse(selector) this on ajax OnSuccess, i did that too. I got $.validator is undefined.
After adding the jquery.validate.js and jquery.validate.unobtrusive.js again in partial view, validation worked. But i do not want to add this in all my partial views.
validate function in JQuery.validate.js has these in first 5 lines apart from validation,
// check if a validator for this form was already created
var validator = $.data(this[0], 'validator');
if ( validator ) {
return validator;
}
I thought of same thing, but i do not know whether what i am proposing is a good one. i want your suggestions in this.
My Idea: After unobtrusive parses the document, why cant i store the $.validator in some global variable and use it in partial views. Sample below,
global variable
var validatorGlobalCache = [];
In jquery.validate.unobtrusive.js, i added the validatorGlobalCache['validator'] to store the $.validator.
$(function () {
$jQval.unobtrusive.parse(document);
validatorGlobalCache['validator'] = $jQval;
});
OnSuccess of ajax load of partial views
function ResetValidationRules(selector) {
if (selector != null && selector != undefined) {
if (validatorGlobalCache != null && validatorGlobalCache != undefined) {
if (validatorGlobalCache['validator'] != null && validatorGlobalCache['validator'] != undefined) {
var unobtrusive = validatorGlobalCache['validator'].unobtrusive;
if (unobtrusive != null && unobtrusive != undefined) {
selector.removeData('validator').removeData('unobtrusiveValidation');
unobtrusive.parse(selector);
}
}
}
}
}
i call this with form id. This works.
is this the correct way to proceed or do you think of anything may go wrong.