从Knockout.js的下拉列表中获取选定的值 [英] Getting selected value from dropdown list in Knockout.js

查看:342
本文介绍了从Knockout.js的下拉列表中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是淘汰赛的新手,从下拉列表中获取选定的值时遇到问题.我试图将值更改为"selectedCity",但正在获取[Object object].谢谢!

I am new to knockout, and have a problem getting a selected value from dropdown list. I tried to change value to 'selectedCity' and I am getting [Object object]. Thanks!

我的HTML

<select data-bind="options: Cities, optionsText: 'CityNameRu', value: selectCity">
</select>

<span data-bind="text: selectedCity"></span>

淘汰赛

function CityModel(data) {
    var self = this;
    this.CityId = ko.observable(data.CityId);
    this.CityNameRu = ko.observable(data.CityNameRu);
    this.CityName = ko.observable(data.CityName);
}

function ViewModel() {
    var self = this;
    self.Cities = ko.observableArray([]);
    self.selectedCity = ko.observable();

    self.selectCity = function (city) {
        self.selectedCity(city.CityNameRu);
    };

    self.GetCities = function () {
        $.ajax({
            type: "GET",
            url: '/FetchCities',
            dataType: "json",
            success: function (data) {
                self.SuccessfullyRetrievedModelsFromAjax(data);

            },
            error: function (err) {
                alert(err.status + " : " + err.statusText);
            }
        });
    };

    this.SuccessfullyRetrievedModelsFromAjax = function (models) {
        ko.utils.arrayForEach(models, function (model) {
            self.Cities.push(new CityModel(model));
        });
    };

JSON响应:

[{"CityId":1,"CityName":"philadelphia","CityNameRu":"Филадельфия"},{"CityId":2,"CityName":"new-york","CityNameRu":"Нью Йорк"}

推荐答案

将整个城市对象设置为selectedCity的值.您还可以添加一个可计算的可观察值以检索文本.

Set the whole city object as value for selectedCity. You can also add a computed observable for retrieving text.

function ViewModel() {
    var self = this;
    self.Cities = ko.observableArray([]);
    self.selectedCity = ko.observable();

    self.selectCity = function (city) {
        self.selectedCity(city);
    };

    self.selectedCityNameRu = ko.pureComputed(function () {
        var selectedCity = self.selectedCity();
        return selectedCity ? selectedCity.CityNameRu : '';
    }, self);

然后在您的html中绑定到selectedCityNameRu

Then in your html bind to selectedCityNameRu

<span data-bind="text: selectedCityNameRu"></span>

这篇关于从Knockout.js的下拉列表中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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