Knockout and MVC - Binding to controls that were renderd using templated editors
I'm just looking at Knockout JS and how I could integrate it with an MVC3 project I'm building.
Looking at the examples where data is brought down from the server, the knockout view model (KVM) is always populated by an Ajax call after the page has been rendered.
Is this the normal way of doing things?
My page cu开发者_运维技巧rrently renders controls using templated editor templates, eg:
@Html.DropDownListFor(m => m.Holiday.Destination, SelectListHelpers.ToSelectList(Model.HolidayModel.Destinations, Model.Holiday.Destination), new { @class = "optionselect", data_bind = "value: Destination" })
However, if using Knockout, shouldn't I be outputting the data that makes up the select list as an array within a script block and then using the knockout binding to fill the select list?
Thanks for any advice on this.
A common and easy way to do this is to serialize your model values to the page. This would be something like:
var viewModel = {
choices: ko.observableArray(@Html.Raw(Json.Encode(Options))),
selectedChoices: ko.observableArray(@Html.Raw(Json.Encode(SelectedOptions)))
};
Then, just use a standard data-bind on your select like:
data-bind="options: choices, selectedOptions: selectedChoices"
精彩评论