Problem

I have a jquery code that calls an endpoint to grab the details of the record using $.getJSON(). I have use this code in several of MVC projects without any problem but in my MVC 2 project it does not trigger my callback at all. I thought it was just a JSON formatting issue because the only way the callback will not trigger if you have incorrect JSON format. But when I test it using fiddler the structure are intact and the endpoint returns the right data. I also check how the data is serialized in the backend and validate if the it contains characters that needs to be encoded to JSON but everything are intact. Here is the sample of my javascript code.

this.GetData = function MyProject$GetData(id, callback){
        
        var successful = false;
        $.getJSON("/Rating/initialize/" + id, 
            null, 
            function(data) {
                result = eval(data);
                
                if (result.error) {
                    DisplayPrompt("Error", result.message);
                    return;
                }
                
                successful = true;
                
                $ratingName.val(result.data.RatingName);
                $ratingCode.val(result.data.RatingCode);
                $xDate.val(result.data.XDate);
                
                if (callback != null && typeof (callback) == "function") {
	                callback(successful);
	}
        });        
    };

Solution

In MVC 2, microsoft added another layer of validation when submitting data to endpoint. Any data that submits data to the endpoint should not allowed to use GET HTTP verb as default. I discover the issue when I use the Request Builder of Fiddler to submit the request to my endpoint. Here are the steps on how to test the endpoint using Fiddler.

  1. Open Fiddler
  2. Click the Request Builder tab
  3. Select GET from the dropdown.
  4. Enter the URL in the address bar and leave the HTTP dropdown and Request Headers textbox as is.
  5. Click Execute button. This will return HTTP 500 error.
  6. Double click the HTTP 500 error in the Web Sessions list. This will launch the Session Inspector.
  7. In the Session Inspector you will see the details of the error. This error is raised by .NET because we violate the JSON behavior settings.

Two Solutions

First, the safest and the easiest way is to change $.getJSON() to $.post(). To test if this solution works, repeat the steps above but on Step #3, change GET to POST. This will return the JSON data instead of the HTML error returned by GET.

Second solution is to set JsonRequestBehavior.AllowGet in Json result see sample below. I recommend the First solution for security reasons.

public ActionResult GetData(byte id)
{
    ...
    ...
    return Json(data, JsonRequestBehavior.AllowGet);
}

Hope this helps!