Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Complex JSON Object to an MVC 3 Action

I am getting some weird results while trying to pass a complex JSON object to an action in MVC 3.

The Locations are populated on the action parameter model, but the name and location are not.

If I do ko.toJS(testViewModel), then the name and location are there, but the locations are blank???

I am using knockout.js:

var testViewModel = {
        Name: ko.observable("Joe Bob"),
        Locations: ko.observableArray([
            { ID: 1, Name: "Salem, OR" },
            { ID: 2, Name: "Big Bear Lake, CA" },
            { ID: 3, Name: "Big Bear City, CA" }
        ]),
        Position: ko.observable("Manager")
    }

Sending it via jQuery ajax:

$.ajax({
            url: "/ClaimsAuthority/Home/TestIt",
            type: "POST",
            data: ko.toJSON(testViewModel),
            success: function (data, status, xhr) {
                //ko.applyBindings(data);
            }
        });

MVC Action:

<HttpPost()>
        Public Function TestIt(model As TestModel) As ActionResult
            Return Json(model)
        End Function

Models:

Public Class TestModel 
    Public Property ID As Integer
    Public Property Name As String
    Public Property Locations As ICollection(Of LocationModel)
    Public Property Position As String  
End Class

Public Class LocationModel
    Public Property ID As Integer
    Public Property Name As String
    Public ReadOnly Property DisplayText As String
        Get
            Return String.Format("({0}) {1}", ID, Name)
        End Get
    End Property
End Class
like image 926
Sam Avatar asked Mar 07 '12 22:03

Sam


1 Answers

Try setting the content type to application/json in your AJAX request:

$.ajax({
    url: '/ClaimsAuthority/Home/TestIt',
    type: 'POST',
    contentType: 'application/json',
    data: ko.toJSON(testViewModel),
    success: function (data, status, xhr) {
        //ko.applyBindings(data);
    }
});
like image 75
Darin Dimitrov Avatar answered Oct 27 '22 11:10

Darin Dimitrov