【发布时间】:2013-11-27 15:16:48
【问题描述】:
我想让我的 SelectList 可观察,这样 ViewModel 会随着对该 SelectList 所做的更改而更新。我在 UI 的下拉列表中看到了显示的值,但我从未看到在我的 ViewModel 中更新了所选值,它始终为空。我在表单上有其他控件可以毫无问题地更新,所以我想知道具体如何使 SelectList 可观察。 SelectLists 和 knockout 似乎与标准输入控件有点不同。
我在课堂上有以下内容:
public string LocationId { get; set; }
public IEnumerable<SelectListItem> Locations { get; set; }
我的位置数组中有以下内容:
private PersonViewModel _viewModel;
public ActionResult Index()
{
var locations = new[]
{
new SelectListItem { Value = "US", Text = "United States" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "MX", Text = "Mexico" },
};
_viewModel.Locations = locations;
return View(_viewModel);
}
我的标记中有以下内容:
<script type="text/javascript">
Person.ViewModel = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model)));
var locationsArray = ko.observableArray(@Html.Raw(Json.Encode(Model.Locations)));
</script>
<form>
<table>
<tr>
<td>
Locations:
</td>
<td>
@Html.DropDownListFor(model => model.LocationId, new SelectList(Model.Locations, "Value", "Text"), new { id = "locationsArray" })
</td>
</tr>
</table>
</form>
【问题讨论】: