in

Platinum Bay

Peace, Love, and Visual Studio ALM

This Blog

Syndication


.NETicated

jQuery and MVC: JSON Form Submission

In my last two posts (jQuery and MVC: JSON and Favorite Image Icons with jQuery and MVC) I covered some basics of jQuery’s AJAX functionality to improve user experience. One of the scenarios which may not seem particularly asynchronous friendly is form submission. Fortunately, jQuery provides for asynchronous post, and in JSON format too.

The complete code to perform this is:

$('form').submit(function(e) {
e.preventDefault();
$.post($(
this).attr("action"), $(this).serialize(), function(json) {
// handle response
}, "json");
});

First, get a jQuery reference to the form element and add a submit event handler:

$('form').submit(function(e) {

Next, we need to cancel the form’s default behavior by using the preventDefault function:

e.preventDefault();
Next, and this is the cool part, we call the post method in jQuery. The post method takes four arguments: url, data, callback, and type. The first three should be familiar from the previous blog posts, but the last one is new. The type parameter specifies the type of data and accepts "xml", "html", "script", "json", "jsonp", or "text". The example above is using JSON.

Rather than hard coding the url, it can be retrieved from the form element itself:

$(this).attr("action")

And rather than manually pulling form fields into the data object, as the form may change, we can call jQuery’s serialize function on the form itself:

$(this).serialize()

Finally, we can tie it all together with an MVC action. This example uses the Employee entity from the Northwind database. Since the identifier on the Employee entity is EmployeeID and not ID, id needs to be specified as an action parameter in order to retrieve the correct employee from the database.

[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Edit(int id, Employee employee)
{
// do work
return new JsonResult { Data = new { Success = true } };
}

One common scenario for this functionality is to provide asynchronous searching within a page. Even asynchronous form submits are possible with jQuery, making your arsenal that much more powerful.

Published Aug 31 2009, 10:33 PM by Steve
Filed under: , ,

Comments

August 31, 2009 8:04 PM

Thanks Steve.  I learned the hard way this weekend that you can also use the $.ajax function instead of $.post if you expect or need to handle errors on form submit.  Apparently, only "success" is ever sent back to calls made to $.post, even in error cases.

 

August 31, 2009 11:06 PM

Hi steve. You can also prevent the default event from firing in jquery by returning false. Which is the recommend jquery way. Just wanted to let you know. Nick

 

September 1, 2009 2:11 AM

Pingback from  Twitter Trackbacks for                 jQuery and MVC: JSON Form Submission - .NETicated         [platinumbay.com]        on Topsy.com

 

September 1, 2009 6:07 AM

Pingback from  Dew Drop – September 1, 2009 | Alvin Ashcraft's Morning Dew

 

September 2, 2009 2:52 PM

Pingback from  ASP.NET MVC Archived Buzz, Page 1

 

September 2, 2009 11:54 PM

Thanks! really cool!

Alexender
 

September 8, 2009 6:44 PM

Just curious, how do you work form input validation into this approach?

Jason
 

September 21, 2009 9:05 PM

Pingback from  ????????????????????? » [Web] ????????????

 

May 22, 2010 1:58 PM

Pingback from  Dodge Colt Auto Car Parts, 1992 Eagle Summit Manual Plymouth Colt

 

May 22, 2010 2:48 PM

Pingback from  Regency Parts Ciera 1987 Oldsmobile Cutlass, Calais Discount 1991 Oldsmobile Cutlass Pontiac Grand Custom Cruiser

 

May 22, 2010 10:51 PM

Pingback from  1998 Ls430 Ls400, 1996 Lexus Ls430

 

May 25, 2010 7:56 PM

Pingback from  1994 Toyota Tercel Used Parts, Tercel Promotion Low - 13.zapstreaming.com

 

May 31, 2010 12:40 AM

Pingback from  1994 - 1993 @ Imperial Grill Vs, 1948 Chrysler Windsor Crown Imperial - 416.eumreborn.com

 

May 31, 2010 2:44 AM

Pingback from  1981 - 1996 @ 190d Satellite Tv, Discount C240 Wiper Blade Mercedes 190d - 233.cmanager.org

 

May 31, 2010 6:36 AM

Pingback from  1996 - 1985 @ 250sl Rent Leather Interior Hemmings Motor News, 250sl Full Episodes Antenna - 43.animejin.com

 

Leave a Comment

(required )  
(optional )
(required )  
Add

About Steve

Steve Andrews is an independent consultant, INETA speaker, and Microsoft MVP for Visual Studio ALM. He has been working in technology for over ten years focusing on custom application development and Application Lifecycle Management. Steve is also Microsoft and IBM certified and a community fanatic having led sessions at nearly 100 events across North America. When he's not developing software solutions or engaging with the community about software technology, Steve is a closet singer and songwriter and plays the guitar and keys. Occasionally, Steve even gets to sleep. Occasionally.
Powered by Community Server (Commercial Edition), by Telligent Systems
© Platinum Bay | Some Rights Reserved Creative Commons License

Disclaimer: The information in this weblog is provided "AS IS" with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my opinion. Feel free to challenge me, disagree with me, or tell me I'm completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever (abusive, profane, rude, or annonymous comments) - so keep it polite, please.