Monday, November 25, 2013

Binding html select using knockoutjs and asp.net mvc


Suppose we have a ViewModel like this

model.user = UserManager.GetUserByID(id);
model.locations = Location.GetLocations();

The markup to populate HTML Select should be
<p data-bind="with: user">
Your country:
<select data-bind="options: $root.availableLocations,
optionsText: 'Text',
optionsValue: 'Value',
value: LocationID,
optionsCaption: 'Choose...'">
</select>
</p>
var userObject = @Html.Raw(Json.Encode(Model.user));
var locationsArray = @Html.Raw(Json.Encode(Model.locations));
var vm = {
user: ko.observable(userObject),
availableLocations: ko.observableArray(locationsArray)
};
ko.applyBindings(vm);

Related Posts :



1 comments on "Binding html select using knockoutjs and asp.net mvc"

Add your comment. Please don't spam!
Subscribe in a Reader
Robert on November 19, 2015 at 1:52 PM said...

I thought it was going to be some boring old post, but it really compensated for my time. front end developers

Post a Comment