jsonasp.net-mvc-2jquery-1.5

$.getJSON() not working with ASP.NET MVC2 in jQuery 1.5


I am trying the new jQuery 1.5 and it broke a few things in my application. I make a call to an action that generates the JSON, but something errors out and causes the script to stop. According to Fiddler and Firebug, the action does return JSON data. I didn't provide the JSON data, but the data is valid according to JSONLint.

Please note that this works as expected in jQuery 1.4.4.

The first thing I noticed was the URL: http://localhost:3219/News/GetAllNewsArchives?callback=jQuery15033185029088076134_1296751219270&_=1296751219672

Script:

// Dropdown box for past articles
$("#article-select").ready(function() {
    $.ajaxSetup({ cache: false });
    $.getJSON('/News/GetAllNewsArchives', null, function(json) {
        var items = "<option value=''>(Select)</option>";
        $.each(json, function(i, item) {
            items += "<option value='" + item.Id + "'>" + subject + "</option>";
        });
        $("#article-select").html(items);
    });
});

Action:

    public ActionResult GetAllNewsArchives()
    {
        return Json(newsRepository.GetAllNewsArchives(), JsonRequestBehavior.AllowGet);
    }

Any ideas of what I am doing wrong?


Solution

  • Okay, I switched to a $.ajax call and I had the same error:

    // Dropdown box for past articles
    $("#article-select").ready(function() {
        $.ajax({
            cache: false,
            type: "POST",
            dataType: "json",
            url: "/News/GetAllNewsArchives",
            success: function(json) {
                var items = "<option value=''>(Select)</option>";
                $.each(json, function(i, item) {
                    items += "<option value='" + item.Id + "'>" + subject + "</option>";
                });
                $("#article-select").html(items);
            }
        });
    

    However, I noticed something on the $.ajax() documentation.

    As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

    I changed my data type from dataType: "json" to dataType: "text json" then it worked.

    Now, I just don't understand why the difference. What does json expect that is different?