Reputation: 15761
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
Upvotes: 6
Views: 5066
Reputation: 1038720
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);
}
});
Upvotes: 15