59

I am calling an ASP.NET MVC action

public JsonResult GetPatient(string patientID)
{
...

from JavaScript using jQuery. The following call works

$.getJSON(
'/Services/GetPatient',
{ patientID: "1" },
function(jsonData) {
  alert(jsonData);
});

whereas this one does not.

$.ajax({
  type: 'POST',
  url: '/Services/GetPatient',
  data: { patientID: "1" },
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('Error loading PatientID=' + id);
  }
});

Both reach the action method, but the patientID value is null w/ the $.ajax call. I'd like to use the $.ajax call for some of the advanced callbacks.

Any thoughts appreciated.

ChrisP
  • 9,796
  • 21
  • 77
  • 121

7 Answers7

36

Content-type

You don't need to specify that content-type on calls to MVC controller actions. The special "application/json; charset=utf-8" content-type is only necessary when calling ASP.NET AJAX "ScriptServices" and page methods. jQuery's default contentType of "application/x-www-form-urlencoded" is appropriate for requesting an MVC controller action.

More about that content-type here: JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks

Data

The data is correct as you have it. By passing jQuery a JSON object, as you have, it will be serialized as patientID=1 in the POST data. This standard form is how MVC expects the parameters.

You only have to enclose the parameters in quotes like "{ 'patientID' : 1 }" when you're using ASP.NET AJAX services. They expect a single string representing a JSON object to be parsed out, rather than the individual variables in the POST data.

JSON

It's not a problem in this specific case, but it's a good idea to get in the habit of quoting any string keys or values in your JSON object. If you inadvertently use a JavaScript reserved keyword as a key or value in the object, without quoting it, you'll run into a confusing-to-debug problem.

Conversely, you don't have to quote numeric or boolean values. It's always safe to use them directly in the object.

So, assuming you do want to POST instead of GET, your $.ajax() call might look like this:

$.ajax({
  type: 'POST',
  url: '/Services/GetPatient',
  data: { 'patientID' : 1 },
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('Error loading PatientID=' + id);
  }
});
nkchandra
  • 5,585
  • 2
  • 30
  • 45
Dave Ward
  • 59,815
  • 13
  • 117
  • 134
  • 1
    Thanks. This solved the problem. I used $.compactJSON() to format the JS object into JSON for the data option. – ChrisP Jul 03 '09 at 18:14
  • As $.compactJSON is not available in jQuery anymore, I used $.toJSON from this plugin here: http://code.google.com/p/jquery-json/ – J. Bruni Sep 03 '10 at 04:07
20

.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc

N.B .load, .get and .post are also simple wrappers around the .ajax method.

redsquare
  • 78,161
  • 20
  • 151
  • 159
11

Replace

data: { patientID: "1" },

with

data: "{ 'patientID': '1' }",

Further reading: 3 mistakes to avoid when using jQuery with ASP.NET

cutts
  • 574
  • 1
  • 5
  • 20
  • 2
    Wouldn't that have to be something like data: '{ patientID: "1" }', to avoid nested double quotes? – Nosredna Jul 02 '09 at 18:49
  • No go. The value is null in the action method with this change. – ChrisP Jul 02 '09 at 19:23
  • try deleting the contentType setting you have specified – redsquare Jul 02 '09 at 19:40
  • I believe the method argument must be the same as the JSON key. i.e. personID. Other than that I'm no sure of the problem because I've used this syntax several times and it works no problems. – cutts Jul 02 '09 at 19:41
  • Having to do this manually is horrible, so I recommend using http://code.google.com/p/jquery-json/ - this lets you wrap your real JSON object with the $.compactJSON() method, which will automatically send the object as a string, reducing headaches all round. – tags2k Jul 02 '09 at 19:48
  • I have the jquery-json plugin and tried it along w/ removing the contentType. The patientID value in the action method is still null. From the debugger, the value of "data" is: "{"patientID":"1"}" I tried experimenting w/ the options further, but still no success. For what it's worth I had another question http://stackoverflow.com/questions/1039105/problem-passing-json-data-using-jquery-ajax-to-net-mvc-action-w-custom-bind where I had a similar problem, but was using the BindingModel on the action method. – ChrisP Jul 02 '09 at 23:14
  • Does anyone know the exact translation of $.getJSON() to $.ajax()? – ChrisP Jul 02 '09 at 23:19
6

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.

$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.

Read More .. jquery-post-vs-get-vs-ajax

Astik Anand
  • 12,757
  • 9
  • 41
  • 51
Vivek
  • 61
  • 1
  • 1
4

The only difference I see is that getJSON performs a GET request instead of a POST.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • Tried changing the type to GET, and the data change in rpcutts answer, but the value is still null in the action method. – ChrisP Jul 02 '09 at 19:31
0
contentType: 'application/json; charset=utf-8'

Is not good. At least it doesnt work for me. The other syntax is ok. The parameter you supply is in the right format.

Mathias F
  • 15,906
  • 22
  • 89
  • 159
0

with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

Northstar
  • 323
  • 4
  • 16