Adventure
Adventure

Reputation: 189

How to deserialize JSON from MVC using JQuery?

Ok, its late Friday afternoon, and I've been fighting this for way too long... I have an MVC2 class that returns a JSON. JQuery throws an error when trying to deserialize it in the browser.

Here's the controller:

<HttpPost()>
Function ChangeAddress(ByVal addressId As Integer) As ActionResult

    ' Build and return JSON containing address.
    Dim v As New TestViewModel With {.Address1 = "My House"}
    Return Json(v)

End Function

Here's the view model:

Public Class TestViewModel

    Public Property Address1 As String

End Class

And here's the script:

// If list is not empty and item was found...
if (found == true) {

         var sum = 14;

    // Get fields of newly selected address.
    $.ajax({
        url: '../../Checkout/ChangeAddress',
        type: 'POST',
        traditional: true,
             data: { addressId: sum },
        success: function (result) {

            var json = result.get_data();
            var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);

            alert("Success!");

        }
    });
};

The deserialization code is from the MVC Music Store example. When executed, JQuery throws an exception on get_data, saying "Object doesn't support this property or method". Ok, so I try commenting out that line and trying deserialize(result). Then exception says "Sys.ArgumentException: Cannot deserialize. The data does not correspond to valid JSON. Parameter name: data".

Where am I going wrong?

Upvotes: 0

Views: 3993

Answers (1)

Matt Ball
Matt Ball

Reputation: 360056

You should not need to explicitly parse ("deserialize") your JSON! jQuery will try to do this automagically, provided that it can correctly guess the dataType returned. You can, of course, specify that you're expecting JSON:

$.ajax({
    url: '../../Checkout/ChangeAddress',
    type: 'POST',
    dataType: 'JSON',               // <========== this line
    traditional: true,
    data: {addressId: sum},
    success: function (result) {

        var json = result.get_data();
        var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);

        alert("Success!");
    }
});

That said - it is possible that the XHR is not coming back with valid JSON. Could you perhaps provide an example of the JSON returned to your jQuery success callback?

Upvotes: 2

Related Questions