[英]ASP.NET MVC model binding with knockout.js
我想用knockout.js 创建的表单元素做一些服务器端模型绑定,使用一些附加到每个动态创建的DOM 元素的自定义名称属性。 我知道我可以使用 AJAX,但原生 HTML 表单帖子现在对我来说效果更好。 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 来做一个类似的版本。 我是 Knockout 的新手,但我搜索了文档以找到一些帮助但没有任何帮助...请帮助...
$index
是一个可观察的,所以你需要解开: $index()
<input type="text"
data-bind="value: type, attr: {name = '['+$index()+'].type'}" />
<input type="text"
data-bind="value: description, attr: {name = '['+$index()+'].description'}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.