Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $.getJSON in .NET MVC 3.0

I want to use jQuery.getJSON function in ASP.NET MVC 3.0, so I wrote the code below for test:

    <input id="btn" type="button" />

<script>
        $("#btn").click(function () {
            $.getJSON("/Location/GetData", null, function (data) {
                alert(data);
            });
        });


</script>

and I have a LocationController with below method:

public JsonResult GetData()
        {
            List<int> result = new List<int>(){1, 4, 5};
            return Json(result);
        }

But it doesn't work! The GetData method calls, but 'alert' is not shown!

like image 550
mdehghani Avatar asked Jun 01 '11 05:06

mdehghani


3 Answers

You need to tell MVC to allow your JSON action to be called via GETs by changing your return to:

return Json(result, JsonRequestBehavior.AllowGet);

By default (for security reasons) they only allow Json to be requested via POSTs.

like image 161
Alconja Avatar answered Oct 15 '22 06:10

Alconja


To protect against cross-side-scripting attacks & JSON Hijacking, MVC 2+ (I think it was 2), requires that you access actions with JSON responses using POST, rather than GET.

You can override this behaviour by using the overload of Json(), where you set the JsonRequestBehavior.AllowGet flag, but as described in the blog post, this is not a good/safe idea.

The way I do all of my JSON requests, whether they be jsut loading data, or posting back, is to use the $.post jQuery method, and limit the controller action to only accept HttpPost.

so your code would become:

$("#btn").click(function () {
    $.post("/Location/GetData", null, function (data) {
        alert(data);
    });
});

and

[HttpPost]
public JsonResult GetData()
{
    List<int> result = new List<int>(){1, 4, 5};
    return Json(result);
}
like image 42
Alastair Pitts Avatar answered Oct 15 '22 07:10

Alastair Pitts


First of all. Install Firebug for Firefox so you can inspect the response the server sends, Chrome and IE has built in tools you can use too.

Without knowing the response I will assume the problem is that ASP.NET MVC protects you against JSON hijacking byt not allowing to return JSON for a GET request by default.

Try changing to:

return Json(result, JsonRequestBehavior.AllowGet);
like image 20
Mikael Eliasson Avatar answered Oct 15 '22 05:10

Mikael Eliasson