Invoking ASP.NET MVC Actions from JavaScript using jQuery

An entry about asp.net mvc | ajax | javascript Publication date 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!

Currently rated 4.2 by 10 people

  • Currently 4.2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS