I've read MSDN documentation of JsonRequestBehavior.AllowGet and many answers here at SO. I experimented and I am still confused.
I have the following action method. It works fine if I use POST method in my ajax call. It fails with status 404 (Resource not found) if I use GET method in my ajax call. So, the question is what exactly does the JsonRequestBehavior.AllowGet enum do in this Json method? The MSDN documentation says: AllowGet HTTP GET requests from the client are allowed. (https://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior(v=vs.118).aspx), but then why does it fail when I use GET method in my ajax call? Changing the attribute from HttpPost to HttpGet does not help, it fails with either POST or GET method.
[HttpPost]
public JsonResult Create(Model m)
{
m.Ssn = "123-45-8999";
m.FirstName = "Aron";
m.LastName = "Henderson";
m.Id = 1000;
return Json(m, JsonRequestBehavior.AllowGet);
}
public class Model
{
public int Id { get; set; }
public string Ssn { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Here is my jQuery ajax call:
$(function () {
console.log("hola");
$("button").on("click", function () {
$.ajax({
method: "POST", //Try changing this to GET and see.
url: "Home/Create",
data: { Id: 123, Ssn: "585-78-9981", FirstName: "John", LastName: "Smith" }
})
.done(function (msg) {
alert("Data Saved: " + msg);
});
});
})
A 404 (Resource not found) means the method is not found (and has nothing to do with JsonRequestBehavior).
Change your ajax to use
$.ajax({
url: "/Home/Create", // note leading forward slash
....
or better, use url: '@Url.Action("Create", "Home")', to correctly generate your url.
404's are due to the attributes, nothing to do with "AllowGet" on the JSON.
You need one or the other [HttpVERB] attributes... not both attributes.
This would work if it is your scenario.
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
You should check out this well documented post
AllowGet will simply allow that JSON response to work over the GET scenario without exception. If you do not, you will see this message:
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.