kbvishnu
kbvishnu

Reputation: 15648

Internal Server Error #500 while trying to display JSONResult with jQuery ajax and MVC

Controller

public JsonResult TeamInfo(string teamName)
            {
                teamDA = new TeamDataAccess();
                var teamInfo = teamDA.TeamInfo(teamName);
               System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
             new System.Web.Script.Serialization.JavaScriptSerializer();
                string sJSON = oSerializer.Serialize(teamInfo);
                JsonResult jsonResult 
=new JsonResult(){ JsonRequestBehavior = JsonRequestBehavior.AllowGet }; 
                    jsonResult.Data = sJSON; // first i give this.
         jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return jsonResult;
                }

Calling Controller from jQuery

$.ajax({
                url: 'Team/TeamInfo/' + teamName,
                success: function (data) {
                    $('#teamDetails').html(data);
                    alert('Load was performed.');
                    $("#dialog-modal").dialog("open");
                }
            });

While debugging I can see it is executing till the last line in controller return jsonResult; But alert('Load was performed.'); is not visible. Do you know what is the reason it is not going into success part. There is no error in server side. Any help is highly appreciated.

EDIT When I added the error in ajax call. it says error 500 (internal server error). How do I find this issue ?

Upvotes: 0

Views: 2947

Answers (2)

Marcelo De Zen
Marcelo De Zen

Reputation: 9507

You don't need to make all the serialization stuff with JavaScriptSerializer.

Your action method could look like this:

 public JsonResult TeamInfo(string teamName)
 {
      return Json(new TeamDataAccess()TeamInfo(teamName), JsonRequestBehavior.AllowGet); 
 }

Upvotes: 3

nemesv
nemesv

Reputation: 139818

The default request type for the $.ajax is GET but by default GET requests are not allowed on JsonResult so you need to excplicitly allow them, with the JsonRequestBehavior property:

JsonResult jsonResult = 
    new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
jsonResult.Data = sJSON;

return jsonResult;

Or you can POST with your ajax call using type: 'POST'

Note: It's still not clear what is your goal with putting the returned JSON directly into the DOM with the line $('#teamDetails').html(data);

Upvotes: 1

Related Questions