开发者

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/Ge开发者_如何学运维tData", 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!


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.


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);
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜