Mikk
Mikk

Reputation: 2229

Kendo data-bind with custom objects in <select> element

I'm just starting with kendo UI and right away got stuck with a rather simple problem. So I have

Code I have so far:

HTML markup:

<form id="change-user">
   <select data-text-field="username" data-bind="source: userList, value: selectedUser">
   </select>
   <label>Username: <input data-bind="value: selectedUser.username"></label>
   <label>Role: 
       <select data-text-field="name" data-value-field="id" data-bind="source: userRoles, value: selectedUser.role"></select>
   </label>
</form>

Javascript:

var model = kendo.observable({
        userList: [
            {
                id: 1,
                username: 'user1',
                role: 1
            },
            {
                id: 2,
                username: 'user2',
                role: 2
            },
            {
                id: 3,
                username: 'user3',
                role: 3
            }
        ],
        selectedUser: null,
        userRoles: [
            {
                id: 1,
                name: 'Admin'
            },
            {
                id: 2,
                name: 'User'
            },
            {
                id: 3,
                name: 'Moderator'
            }
        ]
    });

    kendo.bind($('form#change-user'), model);

But this doesn't seem to work. It seems that property 'selectedUser' gets string value 'user1', 'user2' and so on instead of becoming javascript object.

I know solution to my problem is probably really simple, but I couldn't figure it out - kendo documentation is really massive and I'm not sure which keywords I should google.

Thank you.

Upvotes: 0

Views: 5130

Answers (1)

Brett
Brett

Reputation: 4269

You cannot bind and object to the value of a dropdownlist using declarative syntax on the HTML elements. Kendo expects an object property to be bound which is of a value data type, like string or number. You can however get the behavior you seek by declaring the first dropdownlist in javascript and hooking into its change or select events to bind the selected user to your observable model. Then, the rest of the controls behave the way you expect.

Here's an example of how you should define the first dropdownlist, and here's a link to a working example in jsFiddle: http://jsfiddle.net/PytHq/3/.

$('#users').kendoDropDownList({
    dataSource: userList,
    dataTextField: 'username',
    dataValueField: 'id',
    change: function () {
        model.set('selectedUser', $('#users').data('kendoDropDownList').dataItem());
    }
});

Upvotes: 1

Related Questions