0

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?

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I have to laugh. What da'ya know, I can read the Address1 value directly without explicit parse. Being new to MVC I find all this automagic stuff nice, but also a bit disconcerting. Where is the rule book (potion book?) that explains the magic? Thanks for your quick response.
@Adventure: start with api.jquery.com/jQuery.ajax, specifically the dataType option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.