Asp.net mvc UI说我的observableArray().length一分钟=0,然后下一分钟=1?

Asp.net mvc UI说我的observableArray().length一分钟=0,然后下一分钟=1?,asp.net-mvc,knockout.js,Asp.net Mvc,Knockout.js,我正在使用knockout.js。我声明两个模型对象: (一) (二) 文件准备好后: $(document).ready ( function () { getProducts(); } ); 它调用getProducts,将model.products可观察数组设置为具有单个对象: var getProducts = function () { model.products.removeAll(); model.products.push

我正在使用knockout.js。我声明两个模型对象:

(一)

(二)

文件准备好后:

$(document).ready
(
    function () {
        getProducts();
    }
);
它调用getProducts,将model.products可观察数组设置为具有单个对象:

var getProducts = function () {

    model.products.removeAll();
    model.products.push
    (
        {
            Id: 1,
            Name: "Product 1",
            Description: "A nice product",
            Price: 666.66,
            Category: "Category 1"
        }
    )
}
我有一个呈现ASP.NET局部视图的视图。默认customerModel.currentView为“list”(从我声明的模型对象中可以看到):

setView是这样的:

var setView = function (view) {
    customerModel.currentView(view);
}
<script>
    var testCart = function () {
        alert("There is " + customerModel.cart().length + " item incustomerModel.cart()");
    }
</script>

<div data-bind="if: customerModel.cart().length == 0">There are no items in customerModel.cart( </div>
<button data-bind="click: testCart">Test Cart</button>
当设置为“购物车”时,以下代码呈现局部视图:

<div data-bind="visible: customerModel.currentView() == 'cart'">
    @Html.Partial("ProductCart")
</div>

@Html.Partial(“ProductCart”)
现在是踢球者。ProductCart.cshtml如下所示:

var setView = function (view) {
    customerModel.currentView(view);
}
<script>
    var testCart = function () {
        alert("There is " + customerModel.cart().length + " item incustomerModel.cart()");
    }
</script>

<div data-bind="if: customerModel.cart().length == 0">There are no items in customerModel.cart( </div>
<button data-bind="click: testCart">Test Cart</button>

var testCart=函数(){
警报(“存在“+customerModel.cart().length+”项incustomerModel.cart()”;
}
customerModel.cart()中没有项目
测试车

猜怎么着?显示“customerModel中没有项目”的div是因为customerModel.cart().length==0,但是当我单击按钮时,警报告诉我customerModel.cart().length等于1。

似乎需要更改
cart().push
购物车。push
,就像您使用
模型.products
一样

这就是
observearray
s的工作原理。请参阅

当您调用
cart()
时,它返回一个新数组,其中的值位于可观察值内。您正在将新值推送到该数组中,而该数组正处于丢失状态


您需要通过
ko.observatarray
API调用
push
方法,这样它将通知所有订户该更改,并且新值将添加到
observatarray

中,而无需仔细查看您的代码,
cart().push
sems错误。您正在将
cart
可观察数组物化为常规数组,将一个项目添加到此常规数组,然后将其丢弃。这就是问题所在!谢谢。
var setView = function (view) {
    customerModel.currentView(view);
}
<div data-bind="visible: customerModel.currentView() == 'cart'">
    @Html.Partial("ProductCart")
</div>
<script>
    var testCart = function () {
        alert("There is " + customerModel.cart().length + " item incustomerModel.cart()");
    }
</script>

<div data-bind="if: customerModel.cart().length == 0">There are no items in customerModel.cart( </div>
<button data-bind="click: testCart">Test Cart</button>