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:
Post a Comment