Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to specify the name property using knockout js

I have a bound list using knockoutjs / mvc3

<div data-bind="foreach: phones">
   <input data-bind='value: number' />
</div>

to send this to my controller action which is

[HttpPost]
public ActionResult Index([Deserialize] WizardModel wizard, IStepViewModel step)
{
}

Previously I was able to bind to my List< T > using Jquery by specifying the name on the input which would be

 <input name="Phones[0].Name"
              Phones[1].Number etc..

But I'm now im using knockout I'm not clear how this should work. Anyone steer me in the right direction.

Ta

like image 733
MikeW Avatar asked May 29 '12 06:05

MikeW


People also ask

How do I assign a value to Knockout observable?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.

How do you declare a ViewModel property as observable?

Syntax. You just need to declare ViewModel property with function ko. observable() to make it Observable.

What does KO represent in KnockoutJS?

KO is that it updates your UI automatically when the view model changes.


2 Answers

You can do this using the attr binding in a template or foreach like this assuming your phone numbers are in an observable array.

<input data-bind='attr: { name: "Phones["+$index()+"].Name"}' />

Im also assuming you are using the latest version of knockout so you can use the $index.

This will allow you to name the inputs so they work with MVC model binding.

like image 167
Joel Cunningham Avatar answered Oct 02 '22 13:10

Joel Cunningham


You can use 'uniqueName', build in knockout. Here is the documentation: http://knockoutjs.com/documentation/uniqueName-binding.html

If you want custom binding(for instance unique id generation) you can use custom binding: http://knockoutjs.com/documentation/custom-bindings.html

These are usefull answers for unuqueName and uniqueId: Unique ids in knockout.js templates and Knockout JS "uniqueName" binding - Same name to two fields

My implementation for unique id generation is:

ko.bindingHandlers.uniqueId = {
    init: function (element, valueAccessor) {
        if (valueAccessor()) {
            element.id = ko.bindingHandlers.uniqueId.prefix + (++ko.bindingHandlers.uniqueId.counter);
        }
    },
    counter: 0,
    prefix: "unique_id_"
};

like image 41
charino Avatar answered Oct 02 '22 15:10

charino