MVC JSON method returning invalid JSON to JQuery?

2019-06-07 11:55发布

问题:

I am having problems with Jquery parsing the JSON I am sending back... however, this is very odd because I am using MVC's JSON method.

Here's my setup. I have a very simple function:

$.ajax({
    url: URLd,
    dataType: 'json',
    data: { Year: $('#VehicleYear').val(), Value: request.term },
    success: function (data, textStatus, jqXHR) { alert("Success!"); },
    error: function(XMLHttpRequest, textStatus) {  
        alert(textStatus + ": " + XMLHttpRequest.responseText);  
    }  
});

It always runs the error function which shows:

parsererror: [{"Value":"Toyota","ID":160}]

I cannot figure out why in the world it is doing this... it was working with an older version of JQuery - and I read that the JQuery JSON parser is quite a bit more strict now- but I can't figure out what's wrong with my JSON.

Even if it is wrong, that's very frustrating because I'm using MVC's Json function to generate this:

public ActionResult GetVehicleModels(int Year, int MakeID, string Value = null)
{
    var modlMatchs = (from VMYX in ent.VehicleMakeYearXREFs
                        join VM in ent.VehicleModels
                        on VMYX.VehicleModelID equals VM.VehicleModelID
                        join VMa in ent.VehicleMakes
                        on VM.VehicleMakeID equals VMa.VehicleMakeID
                        where VMYX.ModelYear == Year && VMa.VehicleMakeID == MakeID && VM.VehicleModelName.StartsWith(Value)
                        orderby VMa.VehicleMakeName
                        select new { Value = VM.VehicleModelName, ID = VM.VehicleModelID }).Distinct().Take(10).ToList();

    return this.Json(modlMatchs, "application/json", JsonRequestBehavior.AllowGet);
}

I must be missing something glaringly obvious... still getting the hang of JQuery/MVC but these things are really slowing my progress.

Sure enough, the JQuery result looks as follows (according to Chrome's developer toolbar)

[{"Value":"Toyota","ID":160}]

回答1:

Change your dataType in the jQuery AJAX call to "text json". I suspect there may be a problem with the response content-type header, or something else that's causing jQuery not to acknowledge the dataType as json. Using "text json" will cause jQuery to accept it as plaintext before converting it to a js object.



回答2:

var parsed = jQuery.parseJSON('[{"Value":"Toyota","ID":160}]');

I've just tried the above and it parses it fine, however remember it has returned it as a single record in an array (due to returning an IEnumerable from the C#).