Cie*_*iel 12 jquery razor jquery-templates asp.net-mvc-3 knockout.js
我试图在ASP.NET MVC 3.0中使用Knockout.js(标题放弃了,不是吗?!)
我遇到了一些问题(与新的jQuery Tmpl引擎有关,而不是ASP.NET MVC 3.0).
我在测试中使用了Steve Sanderson的示例程序,并且主要用新的Razor View Engine复制了他的结果(我不相信Razor与我的问题有任何关系).
http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/
但是我想用自然的 jquery绑定做更多的事情,而不是HTML绑定属性.这在knockout的教程中有详细描述. http://knockoutjs.com/documentation/template-binding.html
但是,正如它解释的那样,我无法重现这一点.我将在我的查看代码下面显示.我的问题来自于{{foreach (i, gift) gifts}}
无效的事实.我尝试了很多变种({{foreach (i, gift) gifts()}}
正如我在其他例子中看到的那样).
我正在使用最新的 knockout.js
文件.我正在使用jQuery 1.4.3.
我http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js
用于模板引擎.但是,我也尝试使用tmpl.js
knockous.js网站上包含的相同文件,我得到了相同的结果.
使用jQuery Templating时,根据当前规范,模板不会呈现.
jQuery模板标签文档可在此处找到:http://api.jquery.com/category/plugins/templates/template-tags/
如果有人对我的确切模型感到困惑.如果我{{foreach (i, gift) gifts}}
用{ 替换{foreach gift}}
,那么模型渲染和行为正确,但我不能使用jQuery本机${property}
声明的任何东西.
@model IEnumerable<Knockout.GiftModel>
@using System.Web.Script.Serialization;
@{
View.Title = "Index";
Layout = "~/Views/Shared/_Site.cshtml";
}
<h2>Gift list editor</h2>
<form class="giftListEditor" action="/home/index" method="post" >
<table>
<tbody data-bind="template:'giftRowTemplate'"></tbody>
</table>
<button data-bind="click: addGift">Add Gift</button>
<button data-bind="enable: gifts().length > 0" type="submit">Submit</button>
</form>
<script type="text/html" id="giftRowTemplate">
{{each (i, gift) gifts}}
<tr>
<td>Gift name: <input class="required" data-bind="value: Title, uniqueName: true" /> ${Title} </td>
<td>Price: $ <input class="required number" data-bind="value: Price, uniqueName: true"/></td>
<td><a href="#" data-bind="click: function() { viewModel.removeGift( $value ) }">Delete</a></td>
</tr>
{{/each}}
</script>
<script type="text/javascript">
var initialData = @(new HtmlString(Model.ToJson()));
var viewModel = {
gifts: ko.observableArray(initialData),
addGift: function () {
this.gifts.push({ Title: "", Price: "" });
},
removeGift: function (gift) {
this.gifts.remove(gift);
},
save: function () {
ko.utils.postJson(location.href, { gifts: this.gifts });
}
};
ko.applyBindings(viewModel);
$("form").validate({ submitHandler: function() { viewModel.save() } });
</script>
Run Code Online (Sandbox Code Playgroud)
我会采用不同的方法.我会使用以下行:
<tbody data-bind='template: { name: "giftRowTemplate", foreach: gifts }'></tbody>
Run Code Online (Sandbox Code Playgroud)
代替:
<tbody data-bind="template:'giftRowTemplate'"></tbody>
Run Code Online (Sandbox Code Playgroud)
这样你就不需要{{each (i, gift) gifts}}
在模板中使用给你带来麻烦的那一行.