我在尝试使用Knockout.js与ASP.NET MVC 3.0(标题泄露了,不是吗?!)

http://knockout.js.com

我遇到了一些问题(更多有关新的jQuery TMPL引擎比ASP.NET MVC 3.0)。

我在我的测试使用史蒂夫·桑德森的示例程序,并有大多复制他的结果与新的Razor视图引擎(我不相信剃刀有什么与我的问题)。

HTTP://博客.stevensanderson.com / 2010/07/12 /编辑-A-可变长度列表敲除式/

不过,我想在自然 jQuery的结合做多,而不是HTML绑定属性。中对此有详细的基因敲除的教程中介绍。 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。不过,我也尝试过这种使用包括在knockous.js网站同tmpl.js文件,我也得到了相同的结果。

  

当使用jQuery模板,每当前说明书中,模板不呈现。

jQuery的模板标记文档被发现这里: HTTP:// API。 jquery.com/category/plugins/templates/template-tags/

在防止有人感到困惑我的精确模型。如果我用{{{foreach (i, gift) gifts}}取代{foreach gift}},然后将模型渲染和行为正确,但我不能使用jQuery的本地${property}声明任何东西。

HTML

@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>
有帮助吗?

解决方案

我会不同地接近这一点。我将使用以下行:

<tbody data-bind='template: { name: "giftRowTemplate", foreach: gifts }'></tbody>

代替:

<tbody data-bind="template:'giftRowTemplate'"></tbody>

你不需要使用{{each (i, gift) gifts}}线是给你的麻烦的模板。这样

其他提示

{{each gifts}}代替{{each (i, gift) gifts}}就可以了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top