This is a migrated thread and some comments may be shown as answers.

Getting started with datasource CRUD

17 Answers 1619 Views
Data Source
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Lee
Top achievements
Rank 1
Lee asked on 25 Apr 2012, 03:53 PM
I have spent hours looking at the documentation and examples for datasource CRUD the but cannot seem to get anything working.  Can you see what I am missing below?  I get "update is not a function" error.  I have tried many variations of this code but no luck getting anything to update or delete.

function listMessagesInit(){
     
     var messageDataSource = new kendo.data.DataSource({
       
       transport: {
           read: "/messages/data",
           update: {
       url: function(id, isnew) {
                       return "/messages/markasread/" + id + "/" + isnew ;
                   },
         
               type: "POST"
           },
           destroy: {
               url: "/messages/delete/210643",
               type: "DELETE"
           },
           parameterMap: function(options, operation) {    
               if (operation !== "read" && options.models) {
                   return {models: kendo.stringify(options.models)};
               }
           }              
       },  //not sure what this does or even if I need it       
       error: function(e) {
           alert(e.responseText);
       },           
       schema: {
         model: {
             id: "id",
             fields: {
                 created: "created",
                 message: "message",
                 customer_name: "customer_name",      
                 isnew: "isnew"   
                }
            }
        },
         
       /*change: function () {
                 $("#message_list").html(kendo.render(template, this.view()));
             } */      
      });
 
     $("#message_list").kendoMobileListView({
         dataSource: messageDataSource,
         //pullToRefresh: true,
                   appendOnRefresh: true,
         style: "inset",
         template: $("#message_list_template").text()
     });
      
     $("#markasread").click(function(){
       messageDataSource.update({id: "216099", isnew:"1"});   
       messageDataSource.sync();          
     });

17 Answers, 1 is accepted

Sort by
0
Seminda
Top achievements
Rank 1
answered on 08 May 2012, 09:48 AM
0
Lee
Top achievements
Rank 1
answered on 08 May 2012, 11:10 AM
Yes I have seen this video, however, I am cannot see the code properly and am therefore struggling.
0
Lee
Top achievements
Rank 1
answered on 10 May 2012, 11:08 AM
I have finally figured this out.  To intiate an update on the transport I had to use set,            

$("#markasread").click(function(){     
  selected.set("isnew", read);   
  dataSource.sync();           
});

       
To initiate the destroy on the transport I needed to use remove,

$("#delete").click(function(){
  dataSource.remove(selected);
  dataSource.sync();           
});

Hope this helps someone else.

0
Shankar
Top achievements
Rank 1
answered on 10 May 2012, 12:00 PM
hi,

my i know the code for create. as i am

Struggling with it.

Thanks ,

Shankar

0
Lee
Top achievements
Rank 1
answered on 10 May 2012, 12:24 PM
I haven't created anything yet but from what I have read I think you use create on the transport and then to initiate this you would use something like, datasource.add(); 
 
eg.
dataSource.add({ name: "John Smith", description: "Product Description", address: "123 1st Street" });
dataSource.sync();


Hope this helps
0
Shankar
Top achievements
Rank 1
answered on 10 May 2012, 12:44 PM
Thanks for the replay.

here is my code.. 
  $(document).ready(function () {
            dataSource = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: _WebServiceAddress + "Client/ClientTable"
                    },
                    create: {
                        url: _WebServiceAddress + "Client/Client",
                        type: "POST"
                    }
 
                },
                schema: {
                    model: tmodel
 
                }
 
            });
 
            var tmodel = kendo.data.Model.define({
                Id: "RecId"
 
            });
 
            $("#Create-client").click(function () {
              //  dataSource.add({ ClientName: $("#Create-Name").val(), Address: $("#Create-Address").val() });
                dataSource.add({ ClientName: "John Smith", Address: "123 1st Street" });
               // dataSource.add();
 
                dataSource.sync();
            });
            $("#Client").kendoGrid({
                dataSource: dataSource
 
            });
 
        });

On click of Create button it is not calling server side code and either it showing any error.
 . i am using WCF Rest at server side.



please advice.

0
Lee
Top achievements
Rank 1
answered on 10 May 2012, 01:06 PM
I'm not 100% sure but don't you need to specify ClientName and Address etc in your model?
0
Shankar
Top achievements
Rank 1
answered on 10 May 2012, 01:16 PM
As per " Get Started With The Kendo UI DataSource" posted by kendo team.

it is not required to specify in model. however i have tested by specifying as well but the result is same .. it is not calling server side code but adding on grid.. once you refresh the page it will disappear.
here is model specification:

          var tmodel = kendo.data.Model.define({
                Id: "RecId",
             
                 fields: {
                                        ClientName: { type: "String" },
                                        Address: { type: "String" }
                }
 
            });
Please advise.
0
Lee
Top achievements
Rank 1
answered on 10 May 2012, 01:39 PM
Sorry I cant be of any more help with this as I have not done a create on my own application yet.
0
Shankar
Top achievements
Rank 1
answered on 10 May 2012, 01:42 PM
Thanks for valuable time.

let me try and i will let you know if i find any solution. which may help you...


0
Seminda
Top achievements
Rank 1
answered on 10 May 2012, 01:43 PM
Please check this code this include Add, edit.

<!DOCTYPE html>
<html>
<head>
    <title></title>
  <script src="../../Scripts/kendo.all.min.js" type="text/javascript"></script>
  <link href="../../Content/kendo.common.min.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/kendo.default.min.css" rel="stylesheet" type="text/css" />
  
</head>
<body>
            <div id="example" class="k-content">
            <div id="grid"></div>


            <script>
                $(document).ready(function () {
                    var crudServiceBaseUrl = "http://demos.kendoui.com/service",
                        dataSource = new kendo.data.DataSource({
                            transport: {
                                read: {
                                    url: crudServiceBaseUrl + "/Products",
                                    dataType: "jsonp"
                                },
                                update: {
                                    url: crudServiceBaseUrl + "/Products/Update",
                                    dataType: "jsonp"
                                },
                                destroy: {
                                    url: crudServiceBaseUrl + "/Products/Destroy",
                                    dataType: "jsonp"
                                },
                                create: {
                                    url: crudServiceBaseUrl + "/Products/Create",
                                    dataType: "jsonp"
                                },
                                parameterMap: function (options, operation) {
                                    if (operation !== "read" && options.models) {
                                        return { models: kendo.stringify(options.models) };
                                    }
                                }
                            },
                            batch: true,
                            pageSize: 30,
                            schema: {
                                model: {
                                    id: "ProductID",
                                    fields: {
                                        ProductID: { editable: false, nullable: true },
                                        ProductName: { validation: { required: true} },
                                        UnitPrice: { type: "number", validation: { required: true, min: 1} },
                                        Discontinued: { type: "boolean" },
                                        UnitsInStock: { type: "number", validation: { min: 0, required: true} }
                                    }
                                }
                            }
                        });


                    $("#grid").kendoGrid({
                        dataSource: dataSource,
                        pageable: true,
                        height: 400,
                        toolbar: ["create"],
                        columns: [
                            { field: "ProductName", title: "Product Name" },
                            { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "150px" },
                            { field: "UnitsInStock", title: "Units In Stock", width: "150px" },
                            { field: "Discontinued", width: "100px" },
                            { command: ["edit", "destroy"], title: "&nbsp;", width: "210px"}],
                        editable: "popup"
                    });
                });
            </script>
        </div>




</body>
</html>
0
Seminda
Top achievements
Rank 1
answered on 10 May 2012, 01:46 PM
Details you can find from :

http://demos.kendoui.com/web/grid/editing-popup.html

In your code I didn't see you declared anything called 
_WebServiceAddress 
0
Shankar
Top achievements
Rank 1
answered on 10 May 2012, 01:54 PM
Thanks for the post.

the Create/Update/Destroy is working fine with Inline edit and popup edit but it is not working with normal edit. 

i.e trying to add the record by using datasource.add(), dataSource.sync();

and regarding.

_WebServiceAddress  it has been declared but i have not post the declaration code...
however _WebServiceAddress is working fine with read operation.

0
Nikolay
Top achievements
Rank 1
answered on 30 May 2012, 07:43 PM
I have very specific legacy server-side so I must write my own transport for DataSource, but I can't find how to do that. I've overide the read method but I can't understand how to return paginated data: array of elements for current page and total amount.

many thanks for help
0
Seminda
Top achievements
Rank 1
answered on 31 May 2012, 06:48 AM
you have to set your schema as follows

data bringing class like this

 public class ImportCaseDataViewModel
    {
        public IEnumerable<DebtCase> GridData { get; set; }


        public int TotalCount { get; set; }
        
    }
the schema section like this
   schema: {
                    data: "GridData",// 
                    model: Product,
                    total: "TotalCount"
                } 



See the following sample to get an idea:

 $(function() {
            var crudServiceBaseUrl = "/ImportCase";
            var selectedRow;
            var Product = kendo.data.Model.define({
                id: "Id"
            });
            dataSource = new kendo.data.DataSource({
                serverPaging: true,
                serverSorting: true,
                transport: {
                    read: {
                        cache: false,
                        url: crudServiceBaseUrl + "/GetAll",
                        dataType: "json",
                        type: "POST",
                        data: {
                        //additional parameters sent to the remote service 
                            hasImported: function() { return $("#HasImported").val(); },
                            invoiceNumber: function() { return $("#InvoiceNumber").val(); },
                            name: function() { return $("#Name").val(); }
                        }
                    },
                    update: {
                        cache: false,
                        url: crudServiceBaseUrl + "/Update",
                        type: "POST",
                        data: {
                            debtCase: function()
                            {
                                debugger;
                                return JSON.stringify(selectedRow);
                            }
                        }
                    }
                },
                batch: true,
                pageSize: 10,
                schema: {
                    data: "GridData",
                    model: Product,
                    total: "TotalCount"
                }
            });


            $("#grid").kendoGrid({
                dataSource: dataSource,
                pageable: true,
                sortable: true,
                height: 450,
                scrollable: { virtual: true },
                selectable: true,
                columns: [
                    { field: "Name", title: "Name" },
                    { field: "TotalAmount", title: "Total Amount" },
                    { field: "OutStandingAmount", title: "OutStanding Amount" },
                    { field: "PaidAmount", title: "Paid Amount" },
                    { field: "InvoiceNumber", title: "Invoice Number" },
                    { field: "HasImported", title: "Has Imported" },
                    { command: { text: "Edit", className: "edit-button" }, title: " ", width: "110px" }
                ]
            });


            $("#cancelButton").click(function() {
                clear();
            });
            $("#grid").delegate(".edit-button", "click", function(e) {
                debugger;
                var selectedRow1;
                var sourcegrid = $('#grid').data('kendoGrid');
                sourcegrid.select().each(function() {
                    selectedRow1 = sourcegrid.dataItem($(this));


                });
                var id = selectedRow1.get("Id");
                selectedRow = dataSource.get(id);
                getData();
            });
            $("#searchButton").click(function() {
                dataSource.read();
            });


            var validator = $("#editForm").kendoValidator().data("kendoValidator"),
                status = $(".status");


            $("#saveButton").click(function() {
                if (validator.validate())
                {
                    setData();
                    clear();
                    status.text("Hooray! Data Saved!").addClass("valid");
                } else
                {
                    status.text("Oops! There is invalid data in the form.").addClass("invalid");
                }


            });
            $("#totalAmount").kendoNumericTextBox({
                format: "c",
                decimals: 2
            });
            $("#outStandingAmount").kendoNumericTextBox({
            //format: "c",
                decimals: 2
            });
            $("#paidAmount").kendoNumericTextBox({
            //format: "c",
                decimals: 2
            });


            function getData()
            {
                $("#name").val(selectedRow.get("Name"));
                $("#totalAmount").val(selectedRow.get("TotalAmount"));
                $("#outStandingAmount").val(selectedRow.get("OutStandingAmount"));
                $("#paidAmount").val(selectedRow.get("PaidAmount"));
            }


            function clear()
            {
                $("#name").val("");
                $("#totalAmount").val("");
                $("#outStandingAmount").val("");
                $("#paidAmount").val("");
                $("#invoiceNumber").val("");
                $("#hasImported").val("");
            }


            function setData()
            {
                debugger;
                selectedRow.set("Name", $("#name").val());
                selectedRow.set("TotalAmount", $("#totalAmount").val());
                selectedRow.set("OutStandingAmount", $("#outStandingAmount").val());
                selectedRow.set("PaidAmount", $("#paidAmount").val());
                dataSource.sync();
                //dataSource.read();
            }
        });
0
Mentor Graphics
Top achievements
Rank 1
answered on 01 Jun 2012, 09:39 AM
Hi Seminda,
See following post:
http://www.kendoui.com/forums/ui/grid/problem-with-inline-grid-editiing-and-asp-net.aspx

I'm using the sample in Kedo Grid inline samples as my base code.
i'm getting empty request to the create/update/delete server events.

What am i missing ??
0
Nikolay
Top achievements
Rank 1
answered on 04 Jun 2012, 06:07 PM
Unfortunately I have more complex problem, for server requests I have template like this:
var RequestTemplate = {
    "SessionID": "null",
    "Task": {
        "ObjectID": null,
        "ClassName": null,
        "MethodName": null,
        "Arguments": null
    }
}

So I'm trying something like this as transport:
                            transport:  {
                                read: function(options) {
                                    var request = $.extend({}, RequestTemplate);
                                    console.log('Transport.read');
                                    console.log(options);
                                    request.SessionID = GlobalSession.sessionId;
                                    request.Task = $.extend({}, RequestTemplate.Task);
                                    request.Task.ObjectID = self.tableId;
                                    request.Task.ClassName = "TTableBeds";
                                    request.Task.MethodName = "Fetch";
                                    $.ajax({
                                        url: Config.url,
                                        type: 'POST',
                                        dataType: 'json',
                                        contentType: 'text/plain;charset=utf-8',                
                                        data: JSON.stringify(request),
                                        success: function(data) {
                                            var result = $.map(data.result.value, function(element, index) {
                                                return $.map(element, function(element, index) {
                                                    var object = {
                                                        id: index
                                                    };
                                                    $.each(element, function(index, element) {
                                                        if (element)
                                                            object['field' + index] = element;
                                                        else
                                                            object['field' + index] = '';
                                                    });
                                                    return object;
                                                });
                                            });
                                            options.success({
                                                "d": {
                                                    "results": result
                                                },
                                                "__count": 1200
                                            });
                                        },

But I can't realise how I must provide the data to make it understand that I have much more to display on than only 20 elements batch.
Tags
Data Source
Asked by
Lee
Top achievements
Rank 1
Answers by
Seminda
Top achievements
Rank 1
Lee
Top achievements
Rank 1
Shankar
Top achievements
Rank 1
Nikolay
Top achievements
Rank 1
Mentor Graphics
Top achievements
Rank 1
Share this question
or