ASP.NET MVC模型绑定与knockout.js
问题描述:
我想做一些服务器端模型绑定与knockout.js创建的表单元素,使用附加到每个动态创建的DOM元素的一些自定义名称属性。我知道我可以使用AJAX,但原生HTML表单帖子现在对我来说会更好。 JS文件看起来是这样的:ASP.NET MVC模型绑定与knockout.js
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());
和HTML标记看起来是这样的:
<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>
如果我能达到上述效果,则MVC控制器动作看起来是这样的:
public ActionResult action(MyModelCS model){
// do something
return View();
}
和MyModelCS应该是这样的:
public class MyModelCS {
public string title { get; set; }
public string[] type { get; set; }
public string[] description { get; set; }
}
我刚刚使用jQuery实现了一个类似的版本,但现在我需要使用Knockout.js来做类似的版本。我是新来的淘汰赛,但我搜索的文档找到没有任何的运气有些帮助...请帮助...
答
$index
是an observable,所以你需要解开:$index()
<input type="text"
data-bind="value: type, attr: {name = '['+$index()+'].type'}" />
<input type="text"
data-bind="value: description, attr: {name = '['+$index()+'].description'}" />
感谢nemesv,现在一切正常...... –