Monday 5 December 2011

Calling Controller Action Method with HTTP GET Ajax Request

In this post, we will see how to do Ajax request using HTTP GET method with JSON in ASP.NET MVC3. HTTP GET method to retrieve data in JSON format should never be used for getting sensitive information, the POST method should be used instead. For more information of how to use the POST method, you can read my previous post; Ajax with jQuery and JSON in ASP.NET MVC 3 or Passing Object in JSON to Controller.

First we prepare our controller method that will respond to the Ajax call:
public JsonResult GetDetailsUsingHttpGet(int id)
{
    Team team = teamRepository.Find(id);
    var anonymousTeam = new { TeamId = team.TeamId, Name = team.Name };

    //'JsonRequestBehavior.AllowGet' must be set, otherwise we will get an error message '500 error'
    return Json(anonymousTeam, JsonRequestBehavior.AllowGet);
}
Since MVC version 2, a controller method that is responding to a GET request is not allowed to return JSON format data for security reason. We need to explicitly state that this operation is allowed by setting 'JsonRequestBehavior.AllowGet' in the returning Json() method.

Then our JavaScript codes:
$(document).ready(function () {
    $("#ajaxBtnGetOne").click(function (event) {
        $.ajax({
            type: "GET",
            url: "/Teams/GetDetailsUsingHttpGet/1",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: AjaxGETSucceeded,
            error: AjaxFailed
        });
    });  
});
function AjaxGETSucceeded(objdata) {
    alert('success');
    alert(objdata.TeamId + ' - ' + objdata.Name);
    $('#ajaxDiv').html(objdata.TeamId + ' - ' + objdata.Name);
}
function AjaxFailed(result) {
    alert('an error has occured: ' + result.status + ' ' + result.statusText);
    alert(result.responseText);
}
Note that in the Ajax function we pass a parameter through its 'url' setting; in this example is '1' that will be passed as an 'id' parameter.

No comments: