我有一个状态的下拉列表,其中包含从ViewBag加载的选项。 Knockout正在替换ViewBag对象。我如何能 A.将(IEnumerable)ViewBag.States传递给knockout和 B.修改onclick事件后的下拉列表以显示修改的(IEnumerable)状态。
这是我被困住的地方......提前致谢!
CSHTML
@(Html.DropDownList("State", (IEnumerable<SelectListItem>)ViewBag.States, "Any", new { @class = "fieldState", data_bind = "options: $root.setStates, optionsText: 'st', value: 'fullName'" }))
从onclick事件触发的Javascript
pageViewModel.setDropdown().setStates.push(new SetDropdown());
JS档案
self.setDropdown = ko.observable(new SetDropdown());
function SetDropdown(stateIS02, longName) {
var self = this;
self.setStates = ko.observableArray();
this.st = stateIS02;
this.name = longName;
}
我现在没有想法......
答案 0 :(得分:3)
<p>
State:
<select data-bind="options: $root.states, optionsText: 'Name', optionsValue : 'Id', value: selectedState, optionsCaption: 'Choose...'"></select>
<br />Selected State value:
<span data-bind="text: selectedState"></span>
</p>
<script>
var stateData = @Html.Raw(Json.Encode(ViewBag.States));
</script>
<script type="text/javascript">
// Constructor for an object with two properties
var State = function (id, name) {
this.Id = id;
this.Name = name;
};
var initialState = new Array();
if (stateData.length > 0) {
for (var k = 0; k < stateData.length; k++) {
initialState.push(new State(stateData[k].Value, stateData[k].Text));
}
}
var viewModel = {
states: ko.observableArray(initialState),
selectedState: ko.observable() // Nothing selected by default
};
ko.applyBindings(viewModel);
</script>
答案 1 :(得分:0)
经过数小时的研究,我发现了它!
我在javascript端的click事件上设置了data-bind属性。我现在也在循环中使用push函数来设置状态。
pageViewModel.setStates.push({ shortState : "VA", fullName: "Virginia"}); //will be in a loop
$("#State").attr('data-bind', "options: $root.setStates, optionsText: function(item) { return item.shortState; }, value: function(item){ return item.fullName;}");
ko.applyBindings(pageViewModel);