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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With