How do I get Knockout to bind the value of a select box to a property of a list item?
I have a ASP.NET MVC strongly typed view to IEnermerable of 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'm using, trying to use, knockout to data bind the collection of MyViewModel such that the user can change the Status using a drop down. My view js looks like:
$(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 is
<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'm having is the drop down value is not being bound to Status. on initial page load the drop down value is properly set. i.e. if it's 1 in the database the will have 'Improved' 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 type string everything again works until you get to the controller where all the values of Status are null.