2

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

4
  • What have you tried so far? How does your data look like, controller action, ko view model? Please post some code. Commented 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 mind Commented Aug 23, 2012 at 16:14
  • Do you know about Knockout MVC ? Commented 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. Commented Aug 23, 2012 at 19:01

1 Answer 1

4

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'
    });
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Martin. Can you show me what the SaveContacts posting method in the knockout viewmodel would look like?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.