Reputation: 19212
So I am an ASP.NET developer. First I tried this:
$.getJSON('/Admin/GetPrelimsByJob/109', function (data) {
var template = $('#optionTemplate').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
With a controller method signature of:
[HttpGet]
public JsonResult GetPrelimsByJob(int jobId)
My first error was that the ID was not being parsed and discovered via the ASP.NET engine.
For testing purposes I took a step back and stopped passing an id:
$.getJSON('/Admin/GetPrelimsByJob', function (data) {
var template = $('#optionTemplate').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
With a controller signature of; [HttpGet] public JsonResult GetPrelimsByJob()
My second error was: 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.
I understand I can set the JsonRequestBehavior to GET to fix this but why is this an issue, why is my response different than if I were to do a POST request.
And finally, to get things to work I did:
$.postJSON('/Admin/GetPrelimsByJob', { jobId: 109 }, function (data) {
var template = $('#optionTemplate').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
Where my controller signature was:
[HttpPost]
public JsonResult GetPrelimsByJob(int jobId)
And where my jQuery extension was:
$.postJSON('/Admin/GetPrelimsByJob', { jobId: 109 }, function (data) {
var template = $('#optionTemplate').html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
I knew I get everything working if I switched to a POST request but I am wondering why.
So to recap: 1) Why was my id not being parsed by the ASP.NET engine when passing an id via a GET request.
2)Why do I have to set JsonRequestBehavior to AllowGet to get my request to allow the JSON data to in the response.
3) Why does a POST just work in this scenario, I am getting data and it seems that the RESTful HTTP action verb GET should be the appropriate choice. Not that I am trying to strictly adhere to REST.
Upvotes: 1
Views: 78
Reputation: 41648
2) To make you more conscious about security issues involved with serving json via GET for detailed explanation see here: Why is JsonRequestBehavior needed?
3) By default browsers will not allow you to make cross domain POST's that's why POST's requests are less vulnerable to i.e. CSRF than GET requests thus you don't need to set JsonRequestBehavior at all.
Upvotes: 1