views:

40

answers:

1

Hi

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, have this 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 an error code 500. What's the problem?

Thank you

+5  A: 

If you saw the actual response, it would probably say

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

You'll need to use the overloaded Json constructor to include a JsonRequestBehavior of JsonRequestBehavior.AllowGet such as:

return Json(list, JsonRequestBehavior.AllowGet);

Here's how it looks in your example code (note this also changes your ints to strings or else you'd 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);
}
JustinStolle
This is the correct answer and should be marked accepted.
Graphain
Also mention you can override the JSON behaviour in jQuery to use POST.
Graphain
Right, especially if you're returning anything that may be deemed sensitive, decorate your controller method with `[HttpPost]` and use the jQuery `$.post()` function instead (see http://api.jquery.com/jQuery.post/)
JustinStolle