How to get Knockout to bind select box value to list item property
How do I get Knockout to bind the value of a select box to a property of a list item?
I have a strongly typed ASP.NET MVC view of IEnermerable from MyViewModel and MyViewModel is defined as
public class MyViewModel{
public int Id {get;set;}
public string Name {get;set;}
public int Status{get;set;}
}
I am using, trying to use, a knockout for data binds the MyViewModel collection so that the user can change the status using the dropdown. My js view looks like this:
$(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);
}
}
}
And my markup
<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>
The problem I am facing is the dropdown value not tied to Status. when loading the start page, the dropdown value is set correctly. those. if it's 1 in the database, "Improved" will be selected, but when I get to the "Save" method in my controller, the status for each item (MyViewModel) is 0. If I change the "Status" property to enter a string, it's all over again will work until you go to a controller where all state values are zero.
source to share