Scott
Scott

Reputation: 2760

Kendo MVVM - Simple Value Binding to a DataSource

I want to learn how to bind an input on a page to a data source, in Kendo MVVM. To start simply, say I have the following html:

<div id="configDiv">
    Call:<input data-bind="value: SystemCall" type="text" /><br />
    <button data-bind="click: save">Save</button>
</div>

And the following view model:

var self = this;

    var Model = kendo.data.Model.define({
        id: "SystemId",
        fields: {
            SystemCall: { editable: true }
        }
    });

        self.ViewModel = kendo.observable({
            dataSource: new kendo.data.DataSource({
                transport: {
                    read: "/api/ServiceApi?method=Ref/SystemConfig/",
                    type: "GET"
                },
                schema: {
                    model: Model
                }
            }),
            save: function (e) {
                alert("save config");
            },
        });
        kendo.bind($("#configDiv"), self.ViewModel);

The idea is that the value of SystemCall returned in json format from the read url would be bound to the input field in the html. Something is wrong because this doesn't work. I have scoured the net looking for a simple example to do nothing more complex than this, and can't find it. Any help in how to get started would be greatly appreciated.

Upvotes: 0

Views: 1409

Answers (1)

CodingWithSpike
CodingWithSpike

Reputation: 43718

I don't have a full working example to share, but I can point out a couple things.


Kendo DataSources expect your server to return an array of items, so if your server is returning a single object, for example the JSON:

{
    "SystemId": 1,
    "SystemCall": "one"
}

then it won't know what to do with it because it isn't an array. It expects something like:

[
    {
        "SystemId": 1,
        "SystemCall": "one"
    },
    {
        "SystemId": 2,
        "SystemCall": "two"
    }
]

Your MVVM binding won't work because you bind it to "SystemCall" but your ViewModel object does not have a property named "SystemCall". THose would be inside one of the items in ViewModel.dataSource


Since a DataSource expects to contain an array of data items, it is usually bound to a ListView or Grid widget to display each data item. Each row template in a ListView could have an input element for that system.


In your Model, the id field should be included in the list of fields like this:

var Model = kendo.data.Model.define({
    id: "SystemId",
    fields: {
        SystemId: { type: "number" }, // assuming this is a number.
        SystemCall: { editable: true }
    }
});

I know this isn't a full answer, but I hope this at least gets you heading in the right direction...

Upvotes: 2

Related Questions