ASP.NET MVC JsonResult returns 500

I have this controller method:

public JsonResult List(int number) { var list = new Dictionary<int, string>(); list.Add(1, "one"); list.Add(2, "two"); list.Add(3, "three"); var q = (from h in list where h.Key == number select new { key = h.Key, value = h.Value }); return Json(list); } 

On the client side, this is a jQuery script:

 $("#radio1").click(function () { $.ajax({ url: "/Home/List", dataType: "json", data: { number: '1' }, success: function (data) { alert(data) }, error: function (xhr) { alert(xhr.status) } }); }); 

I always get error code 500. What is the problem?

thanks

+7
json jquery asp.net-mvc
source share
2 answers

If you saw the actual answer, it will probably say

This request is blocked because it can be disclosed to third-party websites when it is used in a GET request. To allow GET requests, set JsonRequestBehavior for AllowGet.

You will need to use the overloaded Json constructor to include JsonRequestBehavior in JsonRequestBehavior.AllowGet , for example:

 return Json(list, JsonRequestBehavior.AllowGet); 

This is how it looks in your code example (note that this also changes your int to string , otherwise you will get another error).

 public JsonResult List(int number) { var list = new Dictionary<string, string>(); list.Add("1", "one"); list.Add("2", "two"); list.Add("3", "three"); var q = (from h in list where h.Key == number.ToString() select new { key = h.Key, value = h.Value }); return Json(list, JsonRequestBehavior.AllowGet); } 
+18
source share

Although JustinStolle's answer solves your problem, I would draw attention to the error provided from the structure. Unless you have a good reason to send your data using the GET method, you should forward it using the POST method.

The fact is that when using the GET method, your parameters are added to the URL of your request instead of adding to the header / body of your request. This may seem like a tiny difference, but a mistake tells you why it matters. Proxies and other potential servers between the sender and the receiver tend to register the request URL and often ignore the headers and / or body of the request. This information is also often considered not important / secret, so any data displayed in the URL is less secure by default.

It is best to send your data using the POST method so that your data is added to the body instead of the URL. Fortunately, this is easy to change, especially since you are using jquery. You can use the $.post wrapper or add the type: "POST" to your parameters:

 $.ajax({ url: "/Home/List", type: "POST", dataType: "json", data: { number: '1' }, success: function (data) { alert(data) }, error: function (xhr) { alert(xhr.status) } }); 
0
source share

All Articles