Tuesday, September 8, 2009 11:49 AM srkirkland

Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

I’m currently working on a project that uses ASP.NET MVC and jQuery to do some Ajax magic, and I ran into a minor (but maybe not obvious) issue when using $.post() against an MVC action that returns a JsonResult.

The core issue is that calling $.get or $.post does not by default treat the returned data as Json, which $.getJSON does. [Also, there is no $.postJSON]

First, let’s setup a little test case using a simple get request.

Calling An Action From jQuery – $.getJSON

   1: function DoAjaxCall() {
   2:     var url = '<%= Url.Action("AjaxTest", "Lookup") %>';
   3:  
   4:     $.getJSON(url,
   5:         null,
   6:         function(data) {
   7:             alert(data.name);
   8:         }
   9:     );
  10: }

Our JavaScript here simple calls $.getJSON(), passing along the action url and expecting back some data with a name property.  The action is implemented as follows:

   1: public ActionResult AjaxTest()
   2: {
   3:     var data = new { name = "TestName"};
   4:  
   5:     return Json(data);
   6: }
 
When we run this, we get the expected result, a little popup that says “TestName”.

Calling the Action using $.post

Let’s make a few changes so that we are posting data to the action and expecting back Json.  The JavaScript changes slightly, with $.getJSON turning into $.post.

   1: function DoAjaxCall() {
   2:     var url = '<%= Url.Action("AjaxTest", "Lookup") %>';
   3:  
   4:     $.post(url,
   5:         null,
   6:         function(data) {
   7:             alert(data.name);
   8:         }
   9:     );
  10: }

All we need to do to the action method is to add an attribute so that it will restrict itself to accepting post requests.

   1: [AcceptPost]
   2: public ActionResult AjaxTest()
   3: {
   4:     var data = new { name = "TestName"};
   5:  
   6:     return Json(data);
   7: }

Note that [AcceptPost] is the same thing as [AcceptVerbs(HttpVerbs.Post)].  It can be found in MVC Contrib.

When we run this example, we get a post to the correct method, but our alert box shows only ‘undefined’.

A trip into FireBug shows that our response was the following: {"name":"TestName"}

Everything looks good there, but the problem is obviously that $.post is not interpreting the return value as JSON.  If you debug into the $.post callback you see that the value of the data parameter is this: "{\"name\":\"TestName\"}".

So it appears the result was stringified.  The fix is to specify the type of data to be returned to the callback function as the fourth parameter to $.post().  Possible values are: "xml", "html", "script", "json", "jsonp", or "text".

Let’s try specifying the type parameter and setting it to ‘json’:

   1: function DoAjaxCall() {
   2:     var url = '<%= Url.Action("AjaxTest", "Lookup") %>';
   3:  
   4:     $.post(url,
   5:         null,
   6:         function(data) {
   7:             alert(data.name);
   8:         },
   9:         'json'
  10:     );
  11: }

Success!  If we look at the POST response it is the same as before, but now we get the proper alert message to display “TestName”.  If we debug through with firebug we see data is now an object with a single property of name (that has the value “TestName”).

AlertJson

What I learned

jQuery’s $.get and $.post do not natively parse the result as JSON.  $.get has a helper called $.getJSON which will do the job for you, though you can achieve the same result by using $.get and passing the string ‘json’ as the fourth “type” parameter.  Since there is no $.postJSON, if you are doing a jQuery ajax post and expecting a JsonResult, you must always pass ‘json’ as the fourth parameter to $.post.

Filed under: , , , , ,

Comments

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Friday, September 11, 2009 12:53 PM by gt1329a

You can use $.ajaxSetup to affect the $.post shortcut.

If you add an $.ajaxSetup({ dataType: 'json' }) one time, all of your $.post calls will attempt to parse JSON.

Alternatively, you might be interested in using a dataFilter in $.ajaxSetup to leverage browser-native JSON parsing in newer browsers.  I've got a post on that:  encosia.com/.../improving-jquery-json-performance-and-security

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Wednesday, March 10, 2010 9:17 PM by Junior Mayhe

It's frustrating to see many incomplete samples like this one, trying to show people how to make Json work on ASP.NET MVC.

Perhaps you could break the curse and improve this article telling people how to accomplish this example and get it working:

1) Install ASP.NET MVC

2) Create a MVC project

3) Add javascripts headers on Views\Shared\Site.master

4) Create a controller named "Lookup"

5) Add the mentioned C# code for AjaxTest() function which returns an ActionResult

6) On Views\Lookup aspx page, create a input button to call javascript DoAjaxCall() function, adding a attribute onclick="DoAjaxCall()"

... and bla bla

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Wednesday, June 30, 2010 10:38 AM by anon

But you left out some steps:

1.) Don't be born too poor to own a computer

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Tuesday, September 21, 2010 1:31 PM by David

var url = '<%= Url.Action("AjaxTest", "Lookup") %>';

This doesn't work, alert shows the value of url = to the full contents of the embedded string, it doesn't resolve to a URL at runtime, is there something I am missing?  Other people might be a stupid as me and need an answer to this... :)

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Monday, September 27, 2010 4:51 PM by srkirkland

@David,

   Maybe this is your problem:  If you use this code in a .js file then <%= ... %> won't "resolve" because those are server-side directives.  Using them in a view (like aspx/ascx) would cause the Url.Action call to work.  If you separate your code into a .js file then you'll have to use another method for discovering your urls (maybe a well-maintained global).

Scott

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Sunday, January 2, 2011 12:56 PM by Ricardo Serradas

Hello, great post! Congrats!

You only forgot to use the parameter JsonRequestBehavior.AllowGet in the JSon method at the Action.

Without it, my javascript is not able to get the response.

Ricardo Serradas

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Tuesday, March 15, 2011 10:37 AM by Jordan

Ricardo,

The method is changed to a post towards the end.

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Friday, April 8, 2011 11:35 AM by weblogs.asp.net

Using jquery ajax methods in asp net mvc get and getjson vs post.. Nice :)

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Monday, May 2, 2011 9:45 PM by weblogs.asp.net

Using jquery ajax methods in asp net mvc get and getjson vs post.. Keen :)

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Thursday, June 16, 2011 3:28 AM by weblogs.asp.net

Using jquery ajax methods in asp net mvc get and getjson vs post.. Great idea :)

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Tuesday, November 8, 2011 11:20 PM by Daniel

Thanks for the post, working after adding JsonRequestBehavior.AllowGet in the JSon method

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Thursday, January 19, 2012 4:11 AM by Benitazz

How do I pass parameters to the controller?

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Tuesday, April 24, 2012 3:28 AM by seppo

having problems as well.... sending parameters to controller

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Wednesday, September 26, 2012 5:57 AM by Raja.Dev

good What is Looking for,

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Tuesday, April 23, 2013 2:17 AM by Donahue

If some one wants to be updated with most recent technologies after that he must be pay a quick visit this web site and

be up to date all the time.

# re: Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post()

Saturday, April 27, 2013 1:33 PM by Rector

I had been advised that to produce the ideal cappuccino you ought to use really

chilled milk - but I can not tell the big difference

in the ones I've made at home. Even though I am a little bit of a novice the cappuccinos I make at home are far better than Starbucks (In My Opinion Anyhow !)