Pass Complex JSON Object for MVC 3 action

I get some weird results when trying to pass a complex JSON object into action in MVC 3.

Locations are populated with an action parameter model, but no name or location is specified.

If I do ko.toJS(testViewModel) , then the name and location are there, but the places are empty.

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 
+6
source share
1 answer

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

 $.ajax({ url: '/ClaimsAuthority/Home/TestIt', type: 'POST', contentType: 'application/json', data: ko.toJSON(testViewModel), success: function (data, status, xhr) { //ko.applyBindings(data); } }); 
+15
source

Source: https://habr.com/ru/post/910213/


All Articles