ASP.NET MVC Tip #5 - Submitting an AJAX Form with jQuery

This is one of the neatest, straightforward, and down right coolest way to submit a form with the ASP.NET MVC Framework. I've blogged in the past about jQuery and how useful it is. Combining MVC with jQuery can produce some really neat Web 2.0 style applications and today we'll take a look at some first steps. I'd like to get into some more advanced usage of jQuery. In particular, how it can integrate with ASP.NET MVC Framework.

Once you've downloaded the latest jQuery library, drop the script into your \Content folder in the MVC project. I usually create a sub folder in Content to organize my javascript files.

Anything you're going to do with jQuery requires this file. Depending on how often you use jQuery on your site, you might want to put the script on your MasterPage or if you only use it on a single page, you could drop it on that specific page.

We will now create a simple action to handle a basic contact form on our site. In this case I put the action in my Home controller. Also notice that by checking the HttpMethod I can handle both the GET and POST of the contact form with the same action. Note: The upcoming release of the MVC framework will not require the ControllerAction attribute on the action.

Looking at the view, we have a very simple contact form to capture the sender's email, the subject, and the body of the message. There's also a submit button to submit the form. We've also created the action using the Url helper.

Next, we are going to create a jQuery handler to wire up the form's submit event and run some jQuery scripts instead of a full server post.

First thing we do with jQuery is make sure the document is ready and all the DOM element have been loaded. Then we find our form element and wire up the "onsubmit" event so we can intercept it and do some jQuery magic. It's really easy to create an AJAX request using the $.post function; we just need some information about the form we're posting. I'm also showing off a couple of cool jQuery functions to do some neat UI updates. We'll fade out the contact form when the AJAX request starts, then fade it back in and show an alert. You can imagine how you could fit progress indicators in here as well.

That's it. When you hit the submit button, the javascript will take over the post and execute the action you specified.

Hope this helps!

0 comments: