2014-03-13 45 views
0

在ASP.NET MVC中,我有一個表單。在這種形式下,用戶選擇一個國家,然後使用正常的@using(Html.BeginForm)將該ID發佈回服務器。更新標籤取決於在淘汰dropdownlist上選定的值與淘汰

但是,對於某些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? :-)

非常感謝!我真的很喜歡學習淘汰賽,但是這一次花了我很長時間!

回答

1

你所做的一切看起來都正確。 現在,您需要定義客戶端視圖模型(其中countryId會ko.observable)和呼叫ko.applyBindings

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

ko.applyBindings(viewModel); 

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