0

我有一个状态下拉列表,其中包含从 ViewBag 加载的选项。Knockout 正在用任何内容替换 ViewBag 对象。我该如何 A. 将 (IEnumerable)ViewBag.States 传递给淘汰赛和 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;
}

我现在没有主意了...

4

2 回答 2

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>
于 2013-10-11T07:23:28.130 回答
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);
于 2013-10-11T15:00:39.690 回答