2016-11-24 121 views
0

试图学习和集成Knockout到ASP.NET Core应用程序。这是最远的,我已经能够按照不同的职位,以获得:Foreach只重复最后一个元素

function DayViewModel(number, name /*others*/) 
{ 
    this.dayNumber = number; 
    this.dayName = name; 
    //others 
} 

var MonthViewModel = function(days /*others*/) 
{ 
    this.monthDays = ko.observableArray(days); 
} 

$(function() 
{ 
    var tempDays = []; 

    @foreach(var day in Model.Days) 
    { 
     string dayName = day.DayNumber.ToString().PadLeft(2, '0') + " - " + Globals.GetDayName(Model.YearNumber, Model.MonthNumber, day.DayNumber, Globals.GetUICulture(Context)); 
     @:tempDays.push(DayViewModel(@day.DayNumber, "@dayName" /*others*/); 
    } 

    var monthViewModel = new MonthViewModel(tempDays /*others*/); 
    ko.applyBindings(monthViewModel); 
}); 

然后,表:

<table id="mTable" class="table"> 
    <thead> 
     <tr> 
      <th>@Html.DisplayNameFor(model => newModel.DayNumber)</th> 
     </tr> 
    </thead> 
    <tbody data-bind="foreach: monthDays"> 
     <tr> 
      <td> 
       <a href="#" data-bind="text: dayName"></a> 
      </td> 
     </tr> 
    </tbody> 
</table> 

这正确生成一个<tr>元素的数组中的相同数量的项目,并且生成的HTML显示tempDays包含所有正确的项目。
为什么Knockout只重复最后一个元素呢?我在文档中无法找到的错误是什么?

回答

1

您将需要创建的MonthViewModel一个新的实例,否则将this在每次调用,这使得最后MonthViewModel变化每个人都被覆盖..

@:tempDays.push(new DayViewModel(@day.DayNumber, "@dayName" /*others*/);

这里是没有剃刀东西提琴:http://jsfiddle.net/LkqTU/32570/

+0

非常感谢,我觉得自己像一个noob。它工作完美 –

-6

使用ng-repeat代替foreach,如果你在angularjs中这样做。 您将在w3school中找到ng-repeat示例和语法。

+0

我不使用AngularJs,所以ng-repeat不适用于我 –