Nate Pet
Nate Pet

Reputation: 46222

Retrieve data from controller and return to ajax call failing

I have the following ajax call in my view:

var obj = { maintId: id };

$.ajax({
    url:  '@Url.Action("EditLog" ,"Maintenance")',
    type: "GET",
    dataType: "json",
    data: obj,
    async: false,
    success: function (data) {
    alert(data.Reason); 
},
error: function (xhr, status, error) {
        alert(xhr.responseText);
        alert(status);
        alert(error);
    }
});

It hits the Action (EditLog) just fine but not able to return the values for SystemID and Reason to the ajax call success data area.

Note that I will be putting values from the DB but for testing, I put hard coded values for SystemID and Reason. When I run the code it goes to the error: function section and I get a parsererror. I am wondering if I am doing anything wrong.

[HttpGet]
public ActionResult EditLog(int maintId)
{        
    return Json(new { SystemID = 1233, Reason = "ReagDegree change" });     
}

Upvotes: 1

Views: 81

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39946

You need to use the JsonRequestBehavior.AllowGet as well:

return Json(new { SystemID = 1233, Reason = "ReagDegree change" }, JsonRequestBehavior.AllowGet);

The JsonRequestBehavior Enum:

Specifies whether HTTP GET requests from the client are allowed.

Which by default is set to Deny get.

https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.jsonrequestbehavior?view=aspnet-mvc-5.2

Upvotes: 1

Related Questions