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
-
What have you tried so far? How does your data look like, controller action, ko view model? Please post some code.nemesv– nemesv2012-08-23 16:14:42 +00:00Commented Aug 23, 2012 at 16:14
-
What have you tried. Perhaps you can give us some of your code to work with so we don't have to try and read your mindGabe– Gabe2012-08-23 16:14:45 +00:00Commented Aug 23, 2012 at 16:14
-
Do you know about Knockout MVC ?Uladzimir Pasvistselik– Uladzimir Pasvistselik2012-08-23 16:19:48 +00:00Commented Aug 23, 2012 at 16:19
-
Guys we are still in the mock-up phase. We do not have our model yet, I am looking ahead at spikes and trying to prepare.mikelus– mikelus2012-08-23 19:01:12 +00:00Commented Aug 23, 2012 at 19:01
Add a comment
|
1 Answer
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'
});
};
2 Comments
mikelus
Thank you Martin. Can you show me what the SaveContacts posting method in the knockout viewmodel would look like?
Martin Devillers
Sure. I've added a save method to my answer as a replacement for the save method from the example. Make sure you take a look at this example -> knockoutjs.com/examples/contactsEditor.html