问题
I think I'm missing something simple, but I can't find any examples showing how to do this... also, please forgive me if some of the terminology I'm using is wrong.
I simply want to use an HTML form that is bound to a Kendo Observable object to create a new record in my remote datasource.
All the examples I've seen show how to edit existing records, but that's not what I'm looking for (at least not at the moment).
I've created a Fiddle http://jsfiddle.net/matbeard/fYfYz/2/ with a simple cut-down version of what I've got so far. Obviously it won't actually save the record as the create URL doesn't point anywhere, but I'm confident I can handle that.
Can somebody please point me in the right direction? Thanks.
And because I can't post a question without it, here's some code copied from the Fiddle:
var model = kendo.data.Model.define({
id: "id",
fields: {
id: { type: 'number' },
field1: { type: 'string' },
field2: { type: 'string' },
field3: { type: 'string' }
}
});
var viewModel = kendo.observable({
dataSource: new kendo.data.DataSource({
type: 'json',
transport: {
create: {
url: '/myurl/create',
dataType: 'json',
type: 'post'
}
},
schema: {
data: 'data',
model: model
}
});
});
kendo.bind($("#my-form"), viewModel);
回答1:
Lets do it slightly different...
- Your form does not need to (should) be bound to the and object containing the
DataSource
since you are actually not saving the dataSource but one record.
So, you should define the model as:
var Model = kendo.data.Model.define({
id: "id",
fields: {
id: { type: 'number' },
field1: { type: 'string' },
field2: { type: 'string' },
field3: { type: 'string' }
}
});
The DataSource
now becomes an object per-se:
var dataSource = new kendo.data.DataSource({
type: 'json',
transport: {
create: "/myurl"
},
schema: {
model: Model
}
});
And your observable object has data
element that is an instance of the Model
defined (new Model()
).
var viewModel = kendo.observable({
data: new Model(),
mySave: function(e){
console.log("this", this.data);
dataSource.add(this.data);
e.preventDefault();
}
});
So, your form should be now something like:
<form id="my-form">
<input name="field1" data-bind="value:data.field1" type="text" />
<input name="field2" data-bind="value:data.field2" type="text" />
<input name="field3" data-bind="value:data.field3" type="text" />
<button data-bind="click: mySave">Save</button>
</form>
Your JSFiddle modiefied http://jsfiddle.net/6LHx3/4/
来源:https://stackoverflow.com/questions/21857910/kendo-mvvm-create-new-record-with-remote-datasource