Asp.Net Mvc3 PartialView Forms with Model Validation, unobtrusive validation and Ajax loaded with JQuery

The built in ASP.Net MVC3 Forms using Model Validation with unobtrusive validation functionality is pretty cool.

However, you might have had some trouble with them when using JQuery to load a PartialView Form into a div.

A trick I’ve found is to load the form into a containing div, then hijax it in a certain way.

Ajax load the html into a div:

<div id="productEditor"></div>

The result should be something like this:

<div id="productEditor">
	<form name="productEditorForm">
	...
	</form>
</div>

After the form html has been loaded into the div, call

$.validator.unobtrusive.parse(this);

Then hijax the form using $(‘#productEditor’).validate();

$('#productEditor').validate({
    submitHandler: function (form) {
        $.post(
			$('#productEditorForm').attr('action'), 
			$('#productEditorForm').serialize(), 			
			function (data) { // this is the callback when saved
				if (data.Message != undefined) {
					if (data.Message == "Saved") {
						console.log('Saved! yay');

						if (savedCallback != undefined)
							savedCallback(data);
					}
				} else {
					// controllers return the form again. so we need to put that back into the div and re-hijax it
					$(divId).html(data);
					hijaxEditor(divId, formId, saveButtonId, savedCallback);
				}
			}
		);
    }
});

Here is a sample ASP.Net MVC3 Visual Studio 2010 project to give you a better idea.

That title is a mouthfull but I guess it describes this post well 🙂

Advertisements

One thought on “Asp.Net Mvc3 PartialView Forms with Model Validation, unobtrusive validation and Ajax loaded with JQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s