【问题标题】:Update label depending on selected value on dropdownlist with knockout根据下拉列表上的选定值更新标签并剔除
【发布时间】:2014-04-18 18:29:43
【问题描述】:

在 ASP.NET MVC 中,我有一个表单。在这种形式中,用户选择一个国家,然后使用普通的@using(Html.BeginForm) 将 ID 发送回服务器。

但是,出于某些 UX 原因,我使用 Knockout。因此,我需要让我的可观察值 countryId 具有下拉列表的值。

我希望我的标签在标记中显示 countryId,具体取决于下拉列表中的选定值。

标记

@Html.DropDownListFor(model => model.SelectedCountry, Model.Countries, new Dictionary<string, object> { { "class", "form-control sendaletter_countrylist" }, { "data-bind", "value:countryId" }})

<label data-bind="text: countryId"></label>

视图模型

 public class CreateSingleLetterModel
    {
        public CreateSingleLetterModel()
        {
            this.Countries = new List<SelectListItem>();
        }

        public string SelectedCountry { get; set; } // expected to be the ID of the SelectListItem
        public List<SelectListItem> Countries { get; set; }
 }

那么我的问题是:

如何修改我的 DropDownListFor,以便自动设置 countryId? :-)

非常感谢!我真的很喜欢学习 Knockout,但是这个花了我很长时间!

【问题讨论】:

    标签: javascript asp.net asp.net-mvc knockout.js


    【解决方案1】:

    您所做的一切看起来都是正确的。 现在您需要定义客户端视图模型(其中 countryId 将是 ko.observable)并调用 ko.applyBindings

    var viewModel = {
        countryId: ko.observable(0)
    };
    
    ko.applyBindings(viewModel);
    

    示例:http://jsfiddle.net/tabalinas/xJ7mm/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      相关资源
      最近更新 更多