Reputation: 1039
Folks, Can anyone help me or direct me to an example of a knockout viewmodel which contains an array of objects being passed to an asp.net mvc action? The only examples I have seen show just simple arrays of strings being passed. Thanks
Upvotes: 2
Views: 2928
Reputation: 18002
Here's an example from the official Knockout site. It's a Contacts editor build with nested arrays. [jsFiddle].
A fitting ASP.NET MVC Action could look like
public ActionResult SaveContacts(IEnumerable<Contact> contacts)
Where Contact is defined as the class:
public class Contact
{
public string firstName { get; set; }
public string lastName { get; set; }
public IEnumerable<Number> phones { get; set; }
}
Where Number is defined as the class:
public class Number
{
public string type { get; set; }
public string number { get; set; }
}
Given the JavaScript Knockout View Model from the example. Your save
method could look like this
self.save = function() {
var jsonString = ko.mapping.toJSON(this.searchParams);
$.ajax({
url: "/MyController/SaveContacts",
data: jsonString,
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
};
Upvotes: 4