Mike Bosch's Blog on .NET

Agile enterprise architecture in .NET, SOA, WCF, WS-*, AJAX, MVC, Sharepoint and more...

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! 

Posted: Feb 15 2008, 01:18 AM by MikeBosch | with 31 comment(s) |
Filed under: , , ,

Comments

Ben Scheirman said:

I'm doing the exact same thing, and yes, it's very easy.

I would be explicit in your actions though.  What you have there is a code-smell where you have 1 action performing 2 distinct functions.

I would have:

/register render "Register"

/register/complete would be the post action, which redirects to /register/completed (or something)

# February 18, 2008 9:13 AM

Mitch Labrador said:

It looks like the controller action is not the point. You can always set the action on the form to whatever you want. The beauty of this for me are are these two functions:

1. f.serialize

2. $.Post(..)

That is pure beauty. I guess this is why jQuery is doing so well, it makes simple things simple to do. Great job!!

# February 19, 2008 9:12 AM

Doug Seelinger said:

First off, great job.  This puts it all together in an easily digestible format.

I'm having a problem, however, getting the callback to 'callback'.  The ajaxStop function works fine, but the 'we're back!' never happens, or rather, it was happening intermittently at one point but now nothing.  I've tried to trace what's happening in FireBug, but I'm not sure where the callback is supposed to happen exactly.

# February 26, 2008 11:30 AM

Eric -> eztiki [at ] hotmail [dot ] com said:

Hi Mike,

I am anxious to get this working, but I experience the following compiler error:

----------------------------------------------------

Compiler Error Message: CS0103: The name 'RenderView' does not exist in the current context

Line 23:         {

Line 24:             // requesting the page

Line 25:             RenderView("ContactUs");

Line 26:         }

Line 27:         else

----------------------------------------------------

What could I be missing? I'm running Windows XP SP1, IE7 Pro, and authoring this for an ASP .NET 2.0 project using Visual Web Developer 2008. Currently testing this script locally.

thanks in advance,

eric

seattle, washington

# March 29, 2008 7:02 PM

Chance said:

Thanks a LOT for this Mike! I have a quick question for you though: using this code example - if I wanted to print something on the server either through a partial view or a simple system out, how could I catch that response from the server with JQuery?

Thanks,

Chance

# March 30, 2008 9:55 PM

skiltz said:

Thanks heaps for posting this.  Worked first time no questions asked! jQuery is my new best friend!

# October 30, 2008 6:20 AM

atifciit said:

Great work done honey. The articles is very much beneficial for beginner of MVC.

# November 17, 2008 5:26 AM

MM said:

Neat article thanks!

# December 25, 2008 8:39 PM

dashavlasov said:

Услуги по оформлению разрешение на применение, пожарный сертификат, строительные лицензии, и еще лицензирование ИСО, сертификат соответствия ГОСТ Р, строительные сертификаты

# March 10, 2009 12:39 PM

rosdi said:

Thanks for the tip on f.serialize(), I didnt know I can do that. Sure helps a LOT!

# March 18, 2009 2:06 AM

yamayka said:

Спасибо, то что нужно.

# April 21, 2009 3:22 AM

Internetagentur said:

Thank you ... this tutorial has me very helped.

# April 29, 2009 1:18 PM

Aziz said:

Great story. Thank u!!!!

# August 9, 2009 2:45 PM

Jijo said:

It shows an error tab function not defined..

var Tag = { init: function() { $("#tagTabs > ul").tabs(defaults = { navClass: "sidebar-tabs-nav", selectedClass: "sidebar-tabs-selected", unselectClass: "sidebar-tabs-nav-item", panelClass: "sidebar-tabs-panel", hideClass: "sidebar-tabs-hide" }); $("#tagTabs").show() }

, dispose: function() { }

};

# August 13, 2009 9:45 AM

r4 firmware said:

Thanx for the valuable information. How to use a jQuery? Please provide information over it. Provide links to related topics if possible.

# October 12, 2009 3:22 AM

cjorellana said:

The name 'RenderView' does not exist in the current context

# February 9, 2010 8:24 PM

sp_412000@yahoo.com said:

awesome... it was really hard for me to find working example.

# April 5, 2010 9:06 AM