我试图让数据库中的值出现在下拉列表中。
我成功地使用表格显示了数据,但是当我添加下拉列表(<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>
Controller :
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);
}
最佳答案
不要对同一上下文应用绑定(bind)两次。将您的 JavaScript 更改为:
ko.applyBindings({
choice: viewModelChoiceJSON,
controlType: viewModelControlTypeJSON
});
在 HTML 中,绑定(bind)选项在 controlType 之前指定 $root:
<select data-bind="options: $root.controlType, optionsText: 'ControlType', optionsCaption: 'CT', optionsValue: 'ControlTypeId'"/>
关于javascript - KnockoutJS 中的下拉列表不具有约束力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16642427/