使用ASP.NET和KnockoutJS从另一个填充1组合框 [英] Populating one combobox from another using ASP.NET and KnockoutJS

查看:79
本文介绍了使用ASP.NET和KnockoutJS从另一个填充1组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它已经被问过,但我一直盯着它几个小时,我无法找到一个可行的解决方案。 Summarising,我收到来自服务器(C#)一个JSON字符串,像这样的:

I know it has been asked before, but it I've been at it for hours and I couldn't find a viable solution. Summarising, I receive an JSON string from the Server (C#), like this:

function CallFromServer() {
$.ajax({
    type: "POST",
    async: false,
    url: "Default.aspx/GetTest",
    data: "{ }",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
            locationsList = jQuery.parseJSON(msg.d);
        }
    });
};

pretty香草,对不对? locationsList的每一个条目包含一个字符串,这是一个国家与另一个列表,包括在这个特定的状态的城市的。我是pretty新KnockoutJS(它甚至不是我的项目,我只是在做一个小的自由职业者),这样瞎搞了一会儿后,我来到了这个结论就如何填充组合框:

Pretty vanilla, right? Each entry of locationsList consists of a string, which is a state and another list, consisting of the cities in this given state. I'm pretty new to KnockoutJS (and it's not even my project, I'm just doing a small freelance), so after messing around for a while, I came to this conclusion on how to populate comboboxes:

HTML

<select id="stateSelect" onchange="GetCities()" style="background-color:#69bed2; width:50px;" data-placeholder="..."
        data-bind="options: stateValue" name="state" class="chosen-select" tabindex="1">
</select>

<select id="citySelect" style="background-color:#69bed2; width:143px;" data-placeholder="Select a state"
              data-bind="options: cityValue" name="city" class="chosen-select" tabindex="2">
</select>

JS:

function CalculatorViewModel()
{
    var self = this;
    CallFromServer(); //Mine
    GetStates(); //Mine

    self.percentBonus = ko.observable(3);
    self.typedValue = ko.observable("0");
    self.bonusValue = ko.observable('');
    self.messageValue = ko.observable("");
    self.stateValue = ko.observableArray(stateArray); //Mine
    self.cityValue = ko.observableArray(cityArray); //Mine

    (...) //A lot of stuff
}

什么是不评论为矿是pretty多那,随着KOJS文档的一些阅读,我用它,以努力实现我想要的东西。

What isn't commented as "Mine" was pretty much there already and along with some reading of the KOJS documentation, I used it in order to try to achieve what I wanted.

好了,现在让我们开始它的要点。人们可能会注意到,我用

Ok, now let's get to the gist of it. One might notice that I used

onchange="GetCities()

在第一选择。下面是它的code:

in the first select. Here's it's code:

function GetCities() {
    cityArray.clear();
    cityArray[0] = '';
    var currentState = $('#stateSelect :selected').text();
    $.each(locationsList, function (i, e) {
        if (e.stateName == currentState) {
            $.each(e.cityList, function (j, city) {
                cityArray[j] = e.cityList[j].cityName;
            });
        }
    });
};

由于espected,无论何时当一个状态改变,self.cityArray更新自己的正确值这个onChange事件引发。不过,组合框,它必然不会刷新,不管是什么。我读过很多关于不同的方式来做到这一点,但我觉得我是如此接近,这种方法是从头开始是不是一种选择。

As espected, whenever this onChange event is raised when a state is changed, self.cityArray updates itself to the proper value. However, the combobox to which it is bound won't refresh, no matter what. I've read a lot about different ways to do it, but I feel that I'm so close with this approach that starting from scratch is not an option.

有没有人有什么我失踪这里的任何想法?

Does anyone have any ideas of what I'm missing here?

顺便说一句,不要担心我stateArray结合,它工作得很好。渲染一套新的选择状态后,由cityArray提供的选项是什么被证明是麻烦。

BTW, don't worry about my stateArray binding, it works just fine. RENDERING the new set of options provided by the cityArray after selecting a state is what is proving to be troublesome.

推荐答案

我想你可能会困惑,淘汰赛是如何工作的,它可以帮助通过的的turorials 的。你似乎在做两件事情,违背了是你的问题的一部分KO的想法:

I think you may be confused as to how Knockout works, it may help going through the turorials. You seem to be doing two things that go against the idea of KO that are part of your problem:


  • 请不要直接连线这样的的onchange 事件,而是用一些敲除构建(如订阅)是什么;

  • 您似乎被清除和重新建的 cityArray 不是 cityValue 观察到的阵列;用户界面将只应对变化后者

  • don't directly wire the onchange event like that, but use some Knockout construct (for example a subscription) for that;
  • you seem to be clearing and repopulating the cityArray instead of the cityValue observable array; the UI will only respond to changes in the latter

此外,你需要:


  • selectedOptions 绑定到一个可观察到绑定到选中状态(S)

  • a selectedOptions binding to bind an observable to the selected state(s)

有些改变我至少表明,在各自的顺序:

Some changes I'd at least suggest, in respective order:

<select id="stateSelect" 
        style="background-color:#69bed2; width:50px;" 
        data-placeholder="..."
        data-bind="options: stateValue, selectedOptions: selectedStates" 
        name="state" 
        class="chosen-select" 
        tabindex="1">
</select>

视图模型需要的东西扩展到持有国的选择:

The view model needs to be extended with something to hold the selection of states:

function CalculatorViewModel()
{
    // Added:
    self.selectedStates = ko.observableArray([]);;       
}

另外删除的onchange 直接事件接线。通过这些方针的东西取代它,订阅到selectedOptions:

Also remove the onchange direct event wiring. Replace it by something along these lines, subscribing to the selectedOptions:

// Use a KO subscription:
self.selectedStates .subscribe(function(newStateValue) {

    // Clear the *observable* array
    self.cityValues.removeAll();

    $.each(locationsList, function (i, e) {
        if (e.stateName == newStateValue) {
            $.each(e.cityList, function (j, city) {
                // Push into the observable array so the UI gets updated
                self.cityValues.push(e.cityList[j].cityName);
            });
        }
    });
});

下面的小提琴以演示如何工作的。

Here's a fiddle to demo how this works.

这篇关于使用ASP.NET和KnockoutJS从另一个填充1组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆