[英]Binding a generic list with knockout.js in MVC5
我正在使用淘汰表.js來顯示購物車中的文章數量。 購物車信息保存在Model ShoppingCartItem的列表中。 因為我沒有讀過直接用knockout.js綁定列表的方法,所以我將列表項推入數組中,然后綁定此數組。
但是,無論我嘗試什么,輸出始終是“您的購物車中有文章”。 因此,不會顯示我數組的長度。
我在捆綁包配置文件中添加了kickout.js:
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-3.3.0.js"));
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout-3.3.0.debug.js"));
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout.validation.js"));
bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
"~/Scripts/knockout.validation.debug.js"));
我的看法Model ShoppingCartItem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OnlineShop.Models
{
public class ShoppingCartItem
{
public Products product { get; set; }
public int amount { get; set; }
}
}
我想將模型綁定與strockout.js結合使用的局部視圖:
@model List<OnlineShop.Models.ShoppingCartItem>
<script type="text/javascript">
var myArray = [];
@foreach (var d in Model)
{
@:myArray.push("@d");
}
var viewModel = {
cartItems: ko.observableArray(myArray)
};
ko.applyBindings(cartItems, document.getElementById("test"));
</script>
<div id="top-cart" class="clearfix">
<div class="shoppingcart-txt">
@if (Model != null && Model.Count() > 0)
{
double sum = 0.0F;
for (int i = 0; i < Model.Count(); i++)
{
sum = sum + (Model[i].amount * Model[i].product.PurchasePrice);
}
<p>
You have <span id = "test" data-bind="text: cartItems().length"> </span> articles in your shopping cart. <br />
<strong>
Sum: @sum.ToString("#,##0.00") EUR <br />
excl. 3.00 EUR shipping costs
</strong>
</p>
}
else
{
<p>
You have no articles in your shopping cart.
</p>
}
</div>
<div class="shoppingcart-img">
<a href="@Url.Action("ShoppingCart", "Home")">
<img src="~/Photos/shoppingcart.png" alt="" border="0" />
</a>
</div>
</div>
我還嘗試將綁定應用於以下內容:
ko.applyBindings(cartItems, document.body);
結果相同。 我的數組長度未顯示。
如果有人能告訴我我做錯了,我將不勝感激。
將綁定更改為: ko.applyBindings(viewModel, document.getElementById("top-cart"));
並將您的腳本移到HTML下方。 創建HTML元素之前先運行它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.