Javascript 在MVC5中使用knockout.js绑定泛型列表
我正在使用knockout.js显示我购物车中的物品数量。购物车信息保存在模型ShoppingCartItem的列表中。 因为我没有读到直接用knockout.js绑定列表的方法,所以我将列表项推到一个数组中,然后绑定这个数组 但无论我尝试什么,输出总是“你的购物车里有物品”。因此,我的数组的长度不会显示 我在bundle配置文件中添加了knockout.js:Javascript 在MVC5中使用knockout.js绑定泛型列表,javascript,jquery,arrays,list,knockout.js,Javascript,Jquery,Arrays,List,Knockout.js,我正在使用knockout.js显示我购物车中的物品数量。购物车信息保存在模型ShoppingCartItem的列表中。 因为我没有读到直接用knockout.js绑定列表的方法,所以我将列表项推到一个数组中,然后绑定这个数组 但无论我尝试什么,输出总是“你的购物车里有物品”。因此,我的数组的长度不会显示 我在bundle配置文件中添加了knockout.js: bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
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"));
我的视图模型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; }
}
}
我想使用knockout.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(viewModel,document.getElementById(“顶级购物车”)代码>
并将脚本移动到HTML下面。它是在HTML元素创建之前运行的
ko.applyBindings(cartItems, document.body);