3

我正在尝试使数据库中的值出现在 dropdownlist 中。我成功地使用表格显示了数据,但是当我添加下拉列表(<select>)时,它停在那里。我无法弄清楚问题所在。

<table>
  <thead><tr>
    <th>Choice Text</th>
    <th>Zero Tolerance Message</th>
    <th>Has SubChoice</th>
  </tr></thead>
  <tbody data-bind="foreach: choice">
    <tr>
     <td>
         <label data-bind="text: ChoiceText,visible:IsUsed"></label>
         <input type="text" data-bind="value: ChoiceText, visible: !IsUsed()" >
     </td>
     <td>
         <label data-bind="text: ZeroToleranceMessage, visible: IsUsed"></label>
         <input type="text" data-bind="value: ZeroToleranceMessage, visible: !IsUsed()" />
     </td>
     <td>
         <label data-bind="text: HasSubChoice, visible: IsUsed"></label>
         <input type="text" data-bind="value: ZeroToleranceMessage, visible: !IsUsed()" />
         <select data-bind="options: controlType, optionsText: 'ControlType', optionsCaption: 'CT', optionsValue: 'ControlTypeId'"/>
     </td>
    </tr>
  </tbody>
</table>

下面是这些脚本:

<script src="~/Content/Scripts/jquery-1.9.1.js"></script>
<script src="~/Content/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Content/Scripts/knockout.js"></script>
<script src="~/Content/Scripts/knockout.mapping-latest.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        $(function () {

            $('th > :checkbox').click(function () {
                $(this).closest('table')
                    .find('td > :checkbox')
                    .attr('checked', $(this).is(' :checked'));
            });
        });

        var viewModelChoiceJSON = ko.mapping.fromJS( $.parseJSON('@Html.Raw(Model.choiceJsonData)'));
        var viewModelControlTypeJSON = ko.mapping.fromJS( $.parseJSON('@Html.Raw(Model.controlTypeJsonData)'));
        //Html.Raw(jsonData)
        ko.applyBindings({ choice: viewModelChoiceJSON });
        ko.applyBindings({ controlType: viewModelControlTypeJSON });
    });

</script>

控制器:

public ActionResult ChoiceList(int? questionId)
{
    _ValidationService = DiFactory.Resolve<IValidationService>();
    _ChoiceService = DiFactory.Resolve<IChoiceService>();
    ChoiceViewModel viewModel = new ChoiceViewModel(_ChoiceService.GetChoice(questionId));
    viewModel.choiceJsonData = JsonConvert.SerializeObject( _ChoiceService.GetChoice(questionId));
    viewModel.controlTypeJsonData = JsonConvert.SerializeObject(_ValidationService.GetControlType());
    //  viewModel.ControlTypeSource = Utility.ControlTypeSource();
    return PartialView("~/Areas/Validation/Views/Choice/ChoiceGrid.cshtml", viewModel);
}
4

1 回答 1

1

不要为同一个上下文应用两次绑定。将您的 JavaScript 更改为:

ko.applyBindings({
    choice: viewModelChoiceJSON,
    controlType: viewModelControlTypeJSON
});

在 HTML 中,绑定选项在 controlType 之前指定 $root:

<select data-bind="options: $root.controlType, optionsText: 'ControlType', optionsCaption: 'CT', optionsValue: 'ControlTypeId'"/>
于 2013-05-20T05:12:10.890 回答