Reputation: 171
I'd like to do some server-side model binding with form elements created with knockout.js, using some custom name attributes attached to each dynamically created DOM element. I know I can use AJAX but native HTML form posts would work out better for me right now. The js file looks like this:
function MyModel(){
var self = this;
var count = 0;
var insertItem = function(eleToInsertAfter){
var index = self.items.indexOf(eleToInsertAfter),
notFound = -1;
var item = {
type: '',
description: ''
};
if(index == notFound){
self.items.push(item); // there are no items yet, just push this item
} else {
self.items.spilce(++index, 0, item); // insert after the 'eleToInsertAfter' index
}
++count;
}
self.title = ko.observable('');
self.items = ko.observableArray([]);
self.insert = function(eleToInsertAfter){
insertItem(eleToInsertAfter);
}
// insert the first item
self.insert({
type: '',
description: ''
});
}
ko.applyBindings(new MyModel());
and the html markup looks like this:
<form method="post" action="/controller/action/">
<input type="text" data-bind="value: title" />
<ol data-bind="foreach: items">
<li>
<!--I'd like to achieve this effect *name="[0].type"* and *name="[0].description"*, and so on -->
<input type="text" data-bind="value: type, *attr: {name = '['+$index+'].type'}*" />
<input type="text" data-bind="value: description, *attr: {name = '['+$index+'].description'}*" /><br />
<button data-bind="click: $root.insert">Add Item</button>
</li>
</ol>
<input type="submit" value="Submit" />
</form>
If I can achieve the above effect then the MVC controller action could look like this:
public ActionResult action(MyModelCS model){
// do something
return View();
}
and MyModelCS would look like this:
public class MyModelCS {
public string title { get; set; }
public string[] type { get; set; }
public string[] description { get; set; }
}
I've implemented a similar version to this using just jQuery but now I'm required to do a similar version using Knockout.js instead. I'm new to Knockout but I searched the documentation to find some help without any luck... please help...
Upvotes: 1
Views: 2706
Reputation: 139788
$index
is an observable so you need to unwrap with: $index()
<input type="text"
data-bind="value: type, attr: {name = '['+$index()+'].type'}" />
<input type="text"
data-bind="value: description, attr: {name = '['+$index()+'].description'}" />
Upvotes: 2