• Aksel Lian
  • 800
  • 0 Comment
  • No tags

Invoking ASP.NET MVC Actions from JavaScript using jQuery

Author: Fredrik Kalseth

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 20 people

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

Comments

8/5/2008 4:21:16 AM

Michael Hart

Simpler:

return Json(new {success = true, message = «Thank you! We value your feedback.»});

Michael Hart Australia

8/5/2008 10:45:22 AM

Fredrik

@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 Smile

Also note that the Json() methods in preview 4 uses the JavaScriptSerializer class internally; my approach uses the JSON.NET framework.

Fredrik Norway

12/19/2008 11:23:35 AM

Alexis

Great post – much less «hack-ish» than a lot of the other tutorials out there.

Alexis South Africa

1/27/2009 2:45:24 AM

pingback

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

devix

Nice Information……….

devix United States

4/3/2009 10:48:36 PM

Jason

Exactly what I needed. Very helpful.

Jason United States

6/22/2009 3:37:46 AM

Praveen

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 Australia

7/10/2009 2:43:46 AM

Paul

Nice blog, just bookmarked it for later reference

Paul Republic of the Philippines

7/10/2009 4:06:13 AM

Paul

BAAAM Nice Post dude! Do more >D

Paul United Kingdom

Invoking ASP.NET MVC Actions from JavaScript using jQuery august 1st, 2016Aksel Lian

En selvstendig webutvikler med en bred variasjon av kunnskaper herunder SEO, CMS, Webfotografi, Webutvikling inkl. kodespråk..



LATEST WORK
oh yea test

daeataetsdfasdf

CLOSE