【问题标题】:How do I use viewbag object and modify with onclick?如何使用 viewbag 对象并通过 onclick 进行修改?
【发布时间】:2013-10-18 17:57:11
【问题描述】:

我有一个状态下拉列表,其中包含从 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;
}

我现在没有想法......

【问题讨论】:

  • 你不要混合服务器端 MVC 和客户端 MVVM

标签: c# .net razor knockout.js


【解决方案1】:
<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>

【讨论】:

  • 这是一个很好的解决方案,但我在燃烧夜间油并进来后想出了答案。
【解决方案2】:

经过数小时的研究,我想通了!

我在 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-12
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多