Monday, November 25, 2013

Binding html select using knockoutjs and mvc

Suppose we have a ViewModel like this

var model = new UserViewModel();
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...'">
<script type="text/javascript">
    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)

Related Posts :

1 comments on "Binding html select using knockoutjs and mvc"

Add your comment. Please don't spam!
Subscribe in a Reader
Robert F. Crocker 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