3

On the server side I have a method that accepts an array of integers and returns a Json object:

public JsonResult GetCorrespondingOfficers(int[] categories){
   //use `categories`
   return Json(model,JsonRequestBehavior.AllowGet);
}

And I have the following script on the client:

        var categories=[1,2,3];
        $.ajax({
        url: url,
        type: 'GET',
        data: { categories: categories },
        contentType: 'application/json; charset=UTF-8',
        dataType: 'json',
        success: function (data) { alert('Success');},
        async: false
    });

When I run the above code I get null for the parameter categories on the server side. If I change the method from GET to POST, then it works. Does it mean that I can't send an array or any Json data with GET request? If not, then what's the problem with my code?

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206

2 Answers2

2

You can send array as a string:

...
data: { categories: JSON.stringify(categories) },
...
phts
  • 3,889
  • 1
  • 19
  • 31
2

GET request does not have message body, so you can't use GET with contentType: 'application/json; charset=UTF-8'. When you use json in GET request, browser breaks your json and append each josn key value to the url(even if you use JSON.stringify method). Therefore for using json and REST you need to use POST method.

hamed
  • 7,939
  • 15
  • 60
  • 114
  • I've totally lost my head. Just 2 days ago, I was able to do that with GET requests. Now the only option that works is the one with POST method. What is more interesting is that it doesn't work when contentType is set to `application/json` – Mikayil Abdullayev Apr 06 '15 at 11:45