1

我正在使用 ASP.NET MVC4 在表中动态生成行。我想使用 Knockout 将所述表的每个生成行中的复选框的启用属性绑定到一个表达式,该表达式正在评估该列中是否有给定数量的复选框。

这是我的表的示例:

<table>
    <tr>
        <th>Happy?</th>
    </tr>
    @for (int z = 0; z < Model.People.Count; z++) { 
    <tr>
        <td>@Html.CheckboxFor(Model.People[z].Happy,new{@data_bind= "checked: CheckedHappyPeople, enable: CheckedHappyPeople.length < 5 || CheckedHappyPeople"})
        </td>
    }
    </tr>
</table>

我的虚拟机:

function viewModel(){
var self = this;
self.CheckedHappyPeople = ko.observableArray();
}

我的模型:

public class PeopleViewModel
{
public List<People> {get; set;}

public PeopleViewModel(){}
}

public class People
{
public bool Happy {get; set;}
}

有了上面的内容,每当我选择“快乐”复选框时,表中的所有复选框都会被选中/取消选中。如何使用 Knockout 绑定到这些动态生成的元素?我应该以某种方式使用foreachASP.NET MVC4 中的绑定吗?

4

1 回答 1

0

You should really try to learn and understand Knockout instead of asking others to write code for you. For one, you aren't learning anything by having someone else do it for you, and two, you don't understand the code that I am writing for you. That being said, this is a solution that others may be looking for in the future so here is the answer.

http://jsfiddle.net/gzsgy/14/

<input data-bind="checked: Selected, enable: $parent.selections() < 5 || Selected()" type="checkbox" />

Keep track of the selections and then disable the checkbox if there are 5 or more selections or it is already checked, so that you can still uncheck it.

于 2013-09-14T15:13:14.833 回答