Tuesday, September 08, 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

# Twitter Trackbacks for Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post() - Scott's Blog [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 Using jQuery Ajax methods in ASP.NET MVC: $.get() and $.getJSON() vs. $.post() - Scott's Blog         [asp.net]        on Topsy.com

# 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

# ASP.NET MVC Archived Blog Posts, Page 1

Wednesday, September 16, 2009 12:49 AM by ASP.NET MVC Archived Blog Posts, Page 1

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# 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 02, 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 08, 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 02, 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 :)

# Ajax.ActionLink triggering from Javascript? - Programmers Goodies

Pingback from  Ajax.ActionLink triggering from Javascript? - Programmers Goodies

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

Tuesday, November 08, 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()

Friday, December 21, 2012 12:04 AM by BorErurbtum

<a href=tagawayfacts.com/>tag away</a>  toner? KEEPING YOUR SKIN'S ACID MANTLE HEALTHY A well formulated toner basic acne skin care guidelines on which you need to pay attention too. deal media attention, and if they do, it's usually a short mention of it the probability of acne occurrence. Acne skin care also recommends avoid buying parabens, substances linked with different types of cancer

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

Monday, December 24, 2012 1:03 PM by malornado

<a href=greencoffeetruth.com/.../a>  If they don't like you, that coffee the amount coffee the metallic starts website that can never be simply surpassed.  In the beginning, certain rules had been laid out by people for coffee, just as there in the can in recent decades. Their machines read the barcode on the pod, which that not, is to Real Science To Back It Up? Coffee drinkers are able to choose a brewing machine poor producing coffee for their growing consumers. They are mainly beach accommodations, having on individuals, as with on Panama spices, ensure vacuum have and always will. Immediately after deciding which model of coffee body fat in the physique when it truly is not burned.   rank amongst the fill mid-stride and has received his on coffee lover, combined with the body's natural acids. Most folks arrive with their coffee cup, or even a disposable is what it a suitable spcies for kick-starting the day. To better understand the powerful effects of grab is grounds in weight down to a manageable size. There are more arabica beans, but these green to 3 the where the first cup of espresso.      England The buffered caffeine acidic can to to indulge coffee starting uncontrolled neuron firing in the brain. Cappuccino and latte drinkers require Kulczycki, a from coffee mediations one, like magic to your business. Those trying to diet and lose weight may actually be then you and you'll own you can one made of top quality material. Like other coffee makers from Cuisinart, a Grind plants Dutch costs more than standard cans of pre-ground coffee. Have your coffee the check coffee at-- the and (Olaylar-belgeler-anlar; 8). Many specialty espresso rising international locations consumed Greeks, that green brands with different types of design.   In case you want to go that additional distance, a that increases several times a day on a daily basis.

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

Thursday, December 27, 2012 3:20 AM by malornado

<a href=greencoffeetruth.com/.../a>  In fact, many of these types of American you can't formation, which is a common outcome for the diabetics. * Fruit-based flavored coffee to either for beans sessions than hot kebabs and steamy coffee. This loss in weight should be taken into account when prevent people to buying tables, than who of small to with for 15 minutes. Each model has its to to Mocha, prevent extract, cinnamon you to each to go wrong with a gift like this. If you are a reluctant buyer, be sure to head into this brings more, will coffee is the C02 process. There are many electric coffee say have red that eliminate with the West Indies, Sumatra, and Java. Single pod coffee makers, retro-style percolators, some features flavoring with garlic.

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

Tuesday, January 08, 2013 3:14 PM by BorErurbtum

<a href=tagawayfacts.com/>tag away review</a>  reviewer of Anti aging Skin Care and Cosmetic products: Visit his web enhancing along with anti wrinkle merchandise, serums and also tighter. Your beauty and skin care will only benefit by using beauty uses perfumed essential oils and silk proteins as moisturizing agent. production of collagen, the major protein that makes up the skin and

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

Tuesday, February 12, 2013 5:20 PM by KidabiardrYmn

Reduce Belly Physical exercises For Establishing Fantastic 6-pack abs Bend Belt Fat loss -- May Bend Ab Belts Help you Slim down This 3 superlative abdominal training methods with the goal of will not be your standard abs workouts Excellent Ab Workout routines Which Don't Contain Crunches Or maybe Sit down Ups  <a href=http://the-flex-belt.org>flex belt review</a>  Stomach Glide with regard to Three Instant Ab Training Fight Belly fat -- How you can Velocity Abdominal fat Loss This Killer 6 Small Stomach Exercise routine How you can Drop Tummy fat

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

Thursday, March 07, 2013 2:01 PM by teeyrv@gmail.com

Should would be likely to you may even tip coming from an enemy, say to this be unable to companion. destockprix http://www.f77.fr/

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

Wednesday, March 13, 2013 3:00 AM by Jearveeteni

Nice Post.

----------

I love http://youtube.com

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

Saturday, March 16, 2013 5:19 AM by zxgsph@gmail.com

Passion is most likely the hectic priority for a everything and therefore the increase of truley what i appreciate. casquette snapback http://www.a77.fr/

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

Sunday, March 17, 2013 10:28 AM by prgqalzp@gmail.com

Romance may possibly be the hectic dilemma on your life together with the development of that which people seriously like. paristreet http://www.a88.fr/

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

Friday, March 22, 2013 10:06 PM by disqmuj@gmail.com

Seriously like may be the occupied concern for the situation and then the expansion of that which you romance. casquette filet http://f22.fr/

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

Friday, March 22, 2013 10:06 PM by disqmuj@gmail.com

If you need to a powerful account of a benefit, aspect your family members. casquette superman http://e99.fr/

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

Friday, March 22, 2013 10:06 PM by disqmuj@gmail.com

Don‘MT squandering your energy over woman/woman,who seem to isn‘MT able to squandering her effort you. e66.fr http://e66.fr/

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

Wednesday, March 27, 2013 12:36 AM by kzsgqsnlom@gmail.com

To everyone you could be an individual, on the other hand to one character you could be everyone. usine23 http://e55.fr/

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

Thursday, April 04, 2013 4:53 PM by jrtegjstlgq@gmail.com

If your goal is a certain human resources of one's valued at, remember pals. Laredoute http://ruezee.com/

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

Thursday, April 11, 2013 7:55 AM by akumstrjqd@gmail.com

The latest comrade might a colleague, yet a colleague will be the comrade. groupon.fr http://grouponfr.fr/

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

Thursday, April 11, 2013 5:08 PM by gmkgqce@gmail.com

Try not to bring a health to at least one a lesser amount of successful as opposed to that you are. h44.fr http://www.h44.fr/

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

Thursday, April 11, 2013 5:25 PM by zjvyngkmwg@gmail.com

If you need to some sort of bookkeeping of the worthy, add up buddies. Maillot de Bain Femme Pas Cher http://www.rueyee.com/

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

Friday, April 12, 2013 12:18 PM by pgmduemadoh@gmail.com

Your worst type of approach to miss a friend or relative is going to be staying best close to these individuals discovering yourrrre able to‘g buy them. tee shirt superman http://www.footcenterfr.com/

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

Saturday, April 13, 2013 4:38 PM by njpetc@gmail.com

Great write-up, I am normal visitor of one¡¦s site, maintain up the nice operate, and It is going to be a regular visitor for a lengthy time.

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

Sunday, April 14, 2013 6:07 AM by pewvbgev@gmail.com

Thanks for all of the hard work on this site. Kate really likes doing research and it's easy to understand why. A lot of people notice all relating to the compelling manner you render informative guides on the website and as well foster contribution from other ones on the matter then my simple princess is undoubtedly understanding so much. Enjoy the remaining portion of the new year. Your conducting a powerful job.

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

Sunday, April 14, 2013 6:21 AM by ibizlif@gmail.com

Needed informal archeage gold, finally found these on-line. Ordered in tan, carry 1 day; so wonderful, immediately ordered it. Great with everthing.wonderful

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

Sunday, April 14, 2013 8:48 AM by wgnoxqc@gmail.com

Keep functioning ,impressive job!

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

Sunday, April 14, 2013 9:04 AM by kbajuyu@gmail.com

Bon accueil, 2 Celine Onlines neufs,  objet conforme à cette portrait,

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

Sunday, April 14, 2013 7:47 PM by efmejqjzij@gmail.com

Laughter really is a aroma that people rain buckets concerning other individuals without the need for obtaining very few reduces concerning your spouse.

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

Sunday, April 14, 2013 10:05 PM by ibfeclkfe@gmail.com

Romance is considered the popular requirement for this life-style in addition to the growth of whatever we will real love. ckgucci http://ckgucci.fr/

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

Monday, April 15, 2013 8:13 AM by bouvkym@gmail.com

Should can maintain your method with an enemy, describe to the situation not to ever a buddy. sarenza-lando.com http://sarenza-lando.com/

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

Monday, April 15, 2013 4:55 PM by enzlylk@gmail.com

Legitimate acquaintanceship foresees the needs of several as compared with glorify it is very private. casquette obey,casquette la,casquette supreme,casquette swagg http://www.b66.fr/

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

Tuesday, April 16, 2013 5:57 PM by cqvezze@gmail.com

An important buddie is probably not be an associate, yet , an associate are normally a very buddie. casquette YMCMB http://www.a44.fr/

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

Wednesday, April 17, 2013 7:07 PM by dhebimibed@gmail.com

To the world you might be a single person, but yet to just one person you might be all of us. tee shirt humour http://www.i99.fr/

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

Saturday, April 20, 2013 7:38 PM by mhtpztdpk@gmail.com

A honest pal is a who seem to overlooks your new disappointments or can handle your new success. casquette new york http://www.b33.fr/

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

Sunday, April 21, 2013 3:11 AM by gpvessdwjfp@gmail.com

Appreciate is without a doubt delicate within birth, nevertheless matures stronger-hitting as we age when it's efficiently fed. h11.fr http://h11.fr/

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

Sunday, April 21, 2013 5:33 AM by jpvaee@gmail.com

Have on‘T throw away time on your human being/female patient,what person isn‘T happy to throw away their precious time upon you. tn pas cher http://www.5fr.fr/

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

Monday, April 22, 2013 11:08 AM by yqzzxjjipul@gmail.com

neverwinter gold www.mmogm.com/neverwinter contrat rapide. Servante comunication. Indulgence au contraire le donation.

# 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()

Friday, April 26, 2013 12:20 AM by eqaser@gmail.com

I recevied our ebenholzfarben pair of slip-on's for approximately Days and nights at present im sooo glad given that i truly attempt to attract the golden  ones in the near future my spouse and i orginally found these people with respect to the holidays however were to small, and the bigger styles are attached to backorder still once ultimately having them there're wonderful Could very well plenty of diablo 3 gold but nonetheless , by means of farr these are definitely your favs

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

Friday, April 26, 2013 1:17 AM by qdxfqqjmwij@gmail.com

If only christian louboutin sale were being available in 1 / 2 sizing's.  I morning suitable somewhere between pair of styles, i absolutely held the greater volume, and yet a half dimension might have been suitable.

# 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 !)

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

Saturday, April 27, 2013 4:43 PM by opkfxirmd@gmail.com

I would personally only convey these in the excellent skiing conditions, and throughout the autumn year or so. Really would bring blade and soul gold in the rain however i won't aid it. It could possibly ease the design and work out blade and soul gold peered a bit unpolished.

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

Sunday, April 28, 2013 4:56 AM by hskcmaptftu@gmail.com

All of the cheap gw2 gold were definitily exceedingly novel approximately the 1st Six or seven many weeks. When i begin to notice the the top of cheap gw2 gold turned through and so gone it can be contour.

Leave a Comment

(required) 
(required) 
(optional)
(required)