在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,但这个花了我很长时间!
答案 0 :(得分:1)
你所做的一切看起来都是正确的。 现在你需要定义客户端视图模型(countryId将是ko.observable)并调用ko.applyBindings
var viewModel = {
countryId: ko.observable(0)
};
ko.applyBindings(viewModel);