Invoking ASP.NET MVC Actions from JavaScript using jQuery
Author: Fredrik Kalseth
31. May 2008 11:27
One of the things that the MVC model is really great at, is integrating with Ajax. I blogged about a RenderJsonResult class a few weeks ago that one could use to create controller actions which render their output as Json – since then the last ASP.NET MVC framework drop also includes a JsonResult type of its own. What I didn’t talk about in the mentioned post, was how to actually invoke such actions from JavaScript; enter jQuery.
Ajax with JQuery
In the crowd of JavaScript libraries out there, JQuery is probably the most unique – at least for now. Its main features are the abilities to query and manipulate the DOM using syntax that anyone familiar with CSS will feel at home with. But jQuery offers more than this – it also has an Ajax API. With this, we can easily perform a POST or GET on a controller action and handle the result it returns asynchronously.
As an example, lets assume we have a FeedbackController with an action Submit:
public ActionResult Submit(string author, string email, string comment)
{
// logic for submitting feedback omitted
return new RenderJsonResult {Result = new {success = true, message = "Thank you! We value your feedback."}};
}
Invoking this from JavaScript using jQuery is super easy:
$.ajax(
{
type: "POST",
url: "/Feedback/Submit",
data:"author=" + author + "&email=" + authorEmail + "&comment=" + comment,
success: function(result)
{
if(result.success) $("#feedback input").attr("value", ""); // clear all the input fields on success
$("#feedback_status").slideDown(250).text(result.message); // show status message with animation
},
error : function(req, status, error)
{
alert("Sorry! We could not receive your feedback at this time.");
}
});
We set the type of the call to POST, because we need to send some data with our request, which we use the data option to specify. jQuery allows us to provide a few callback methods that will be invoked on the success or failure of the Ajax call. If our call is successful, the success callback gets invoked, which gets passed an object representing the result of the Ajax call. jQuery is able to handle results formatted in different styles, including xml, html, script and json. You can specify the expected data type using the dataType option. Leaving it out will cause jQuery to choose the type based on the MIME type of the response, which is usually fine. There are other options which can be used; you’ll find a complete description of them here. The code in the success callback uses the selectors, attributes, manipulation and effects APIs to reset the input fields and tell the user that the feedback was received.
It’s simple, it’s elegant – and so, so far removed from the bloated UpdatePanels of ASP.NET.
Surface Scratched
This post merely scratches the surface of what is possible when combining ASP.NET MVC with jQuery (or other Ajax APIs for that matter). Look out for more posts on this topic in the future!
Comments
This post is also available in: English
8/5/2008 4:21:16 AM
Simpler:
return Json(new {success = true, message = «Thank you! We value your feedback.»});
Michael Hart
8/5/2008 10:45:22 AM
@Michael: Yeah, you’re right – but this post was written using the preview 2 of the ASP.NET MVC framework; they didn’t add the Json() methods until later
Also note that the Json() methods in preview 4 uses the JavaScriptSerializer class internally; my approach uses the JSON.NET framework.
Fredrik
12/19/2008 11:23:35 AM
Great post – much less «hack-ish» than a lot of the other tutorials out there.
Alexis
1/27/2009 2:45:24 AM
Pingback from goneale.wordpress.com
Submitting an AJAX Form with ASP.NET MVC + jQuery « {Programming} & Life
goneale.wordpress.com
4/1/2009 2:47:42 PM
Nice Information……….
devix
4/3/2009 10:48:36 PM
Exactly what I needed. Very helpful.
Jason
6/22/2009 3:37:46 AM
I believe you need to add the below definitions while doing a jQuery .ajax
contentType: «application/json; charset=utf-8»,
dataType: «json»
I needed the above to make it work, esp. processing the returned result at the
Javascript end.
-Praveen
Praveen
7/10/2009 2:43:46 AM
Nice blog, just bookmarked it for later reference
Paul
7/10/2009 4:06:13 AM
BAAAM Nice Post dude! Do more >D
Paul