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
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.
Syntax. You just need to declare ViewModel property with function ko. observable() to make it Observable.
KO is that it updates your UI automatically when the view model changes.
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.
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_"
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With