0

我正在尝试使用 knockoutjs 绑定复选框列表。我有一个与配置文件列表相关的用户,我想要的是在加载页面时使用用户配置文件初始化复选框列表。

这是我的代码

var userProfileList = [];
var jsonUserAdminModel = null;
var viewModel = {
    ,firstName: ko.observable()
    ,lastName: ko.observable()
    ,userId: ko.observable()
    ,userProfiles: ko.observableArray(userProfileList)
    ,result: ko.observable()
};

viewModel.result = ko.computed(function () {
    jsonUserAdminModel = {
        UserId: (this.userId() != undefined ? this.userId() : null)
        ,FirstName: (this.firstName() != undefined ? this.firstName() : null)
        ,LastName: (this.lastName() != undefined ? this.lastName() : null)            
    }
    return jsonUserAdminModel;
}, viewModel);

$(document).ready(function () {               
        ko.applyBindings(viewModel);
        //Init the list of all profiles
        viewModel.userProfiles(@Html.Raw(Json.Encode(Model.Profiles)));
    });

HTML

<div id="UserProfiles" data-bind="foreach: userProfiles" style="margin: 10px">
    <input type="checkbox" data-bind="value: ProfileId" /><span data-bind="text: Name"></span>
</div>

我想检查用户默认配置文件并绑定它。

谢谢。

4

1 回答 1

0

You're going to want to bind your input to a checked observable on the user profile object. To do that, you're going to need to create a profile viewmodel and convert your raw data into instances of that viewmodel so that their properties can be made observable. You could also use the ko.mapping plugin to achieve this.

Then your HTML would look something like this:

<div id="UserProfiles" data-bind="foreach: userProfiles" style="margin: 10px">
    <input type="checkbox" data-bind="attr: {value: ProfileId() }, checked: isChecked" /><span data-bind="text: Name"></span>
</div>
于 2012-12-05T17:34:12.640 回答