3
如何獲取Knockout以將選擇框的值綁定到列表項的屬性?如何獲取Knockout將選擇框的值綁定到列表項的屬性
我有一個ASP.NET MVC強類型的視圖MyViewModel和MyViewModel的IEnermerable被定義爲
public class MyViewModel{
public int Id {get;set;}
public string Name {get;set;}
public int Status{get;set;}
}
我使用,欲以,淘汰賽將數據綁定MyViewModel的集合使得用戶可以使用下拉菜單更改狀態。我的觀點JS的樣子:
$(document).ready(function() {
ko.applyBindings(new ViewModel());
});
var statusItems = [
{ id: 0, name: 'New' },
{ id: 1, name: 'Improved' },
{ id: 2, name: 'Bad' }
];
function ViewModel() {
var self = this;
self.Items = ko.observableArray(@Html.Raw(Json.Encode(Model)));
self.statuses = statusItems;
self.remove = function() {
if (confirm('Are you sure you want to remove the entry?\nThis operation cannot be undone.')) {
self.Items.remove(this);
}
}
}
而且我的標記是
<div id="dashboard-div">
@using (Ajax.BeginForm("Save", "Dashboard", new AjaxOptions { HttpMethod = "Post" }, new { id = "dashboardForm" }))
{
<table>
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: Items">
<tr>
<td><span data-bind="text: Name" /><input type="hidden" data-bind="value: Id, attr: { name: '['+$index()+'].Id'}" /></td>
<td>
<select id="status-dropdown" data-bind="options: $parent.statuses, optionsText: 'name', optionsValue: 'id', value: Status" />
</td>
</tr>
</tbody>
</table>
</div>
<button data-bind="enable: Items().length > 0" type="submit">Save</button>
}
</div>
我遇到的問題是下拉值不會被綁定到狀態。在初始頁面加載時,正確設置下拉值。即如果數據庫中的值爲1,將會選擇「改進」,但是當我到達控制器中的Save方法時,每個項目(MyViewModel)的狀態爲0.如果我將Status屬性更改爲鍵入字符串,到狀態的所有值爲空的控制器。
*嘆*我就看出我問我會找出我的問題。我需要將屬性名稱添加到select以便模型綁定可以工作。 –
很高興你解決了它。你可以將它添加爲答案並接受它嗎?這樣你的問題就不會出現在未解決的Knockout問題列表中。 –