简体   繁体   中英

How to make Kendo Datasource request from server side API call using Kendo MVVM and c#?

I am using HTML page as a front end and i have to transfer a row of json data to database, how should i transfer a row full of values as a parameters to server side function or request datasource from server side to populate entities?

Here is my html code :

   <div id="example">
    <div id="kendoGrid"
         data-role="grid"
         data-pageable=" true"
         data-sortable=" true"
         data-filterable="true"
         data-toolbar="['create','save', 'cancel']"
         data-editable="inline"
         data-columns="[

      { 'field': 'Id', 'width': 100 },
              { 'field': 'ShortName', 'width': 100 },
          { 'field': 'FullName', 'width': 100 },
       { 'field': 'ContactPerson', 'width': 100 },
            { 'field': 'CurrentCurrencyCode', 'width': 100 },
       { 'field': 'Adress1', 'width': 100 },
       { 'field': 'CompanyCity', 'width': 100 },
         { 'field': 'CompanyState', 'width': 100 },
          { 'field': 'CompanyCountry', 'width': 100 },
          { 'field': 'ZipPostCode', 'width': 100 },
      { 'field': 'TelArea', 'width': 100 },
      { command: ['edit', 'update'], title: 'Actions', width: '250px' },

     ]"
         data-bind="source: products"
         style=" height :500px"></div>
</div>

Here is my code of view model that success fully populate grid

   document.onreadystatechange = function () {



var viewModel = kendo.observable({

    products: new kendo.data.DataSource({

        schema: {
            //data:"Data",
            total: "Count",

            model: {
                Id: "Id",
                fields: {
                    Id: { type: "int" },
                    ShortName: { editable:true, type: "string" },
                    FullName: { editable: true, type: "string" },
                    ContactPerson: { editable: true, type: "string" },
                    CurrentCurrencyCode: { editable: true, type: "int" },
                    Adress1: { editable: true, type: "string" },
                    CompanyState: { editable: true, type: "string" },

                    CompanyCity: { editable: true, type: "string" },
                    CompanyCountry: { editable: true, type: "string" },
                    ZipPostCode: { editable: true, type: "string" },
                    TelArea: { editable: true, type: "string" }

                }
            }
        },
        batch: true,

        transport: {

            read: {
                url: "/api/Companies/GetAllCompanies",
                dataType: "json"
            },
            create: {
                type: 'POST',
                // data: { request: {defcompny} , type: "create" },
                url: "/api/Companies/SaveDefCompny", // here you need correct api url
                dataType: 'json'
                //contentType:"json"
            },
            //update: {
            //    url: "/api/Companies/SaveDefCompny", // here you need correct api url
            //    dataType: "json"
            //},
            destroy: {
                url: "/api/Companies/Delete", // here you need correct api url
                dataType: "json"
            },
            parameterMap: function (data, operation) {

                if (operation !== "read" && data) {
                    debugger;
                    //return kendo.stringify({ defcompny: data.models[0] });
                    return JSON.stringify({ product: data.models[0] });
                    //return {"defcompny": "mydata" };
                }
            }
        }

    }) 


});
    // var gridData = viewModel.product;

    kendo.bind(document.getElementById("example"), viewModel);

    }

Here is my server side code that i am using its entities must be filled with values when i make a call request or how to make a datasource request to populate entities?

  [HttpPost]
    //product must have the values on view model operation create call and sending product data but it is null 
    public string SaveDefCompny( DefCompanyDTO product)
    {



        //return defcompny.save();
        RPDBEntities data = new RPDBEntities();
        var def = new DefCompany();
        {
            def.Id = product.Id;
            def.CurrentCurrencyCode = product.CurrentCurrencyCode;
            def.ShortName = product.ShortName;
            def.FullName = product.FullName;
            def.ContactPerson = product.ContactPerson;
            def.Address1 = product.Address1;
            def.CompanyCity = product.CompanyCity;
            def.CompanyState = product.CompanyState;
            def.CompanyCountry = product.CompanyCountry;
            def.ZipPostCode = product.ZipPostCode;
            def.TelArea = product.TelArea;
        }
        data.DefCompanies.Add(def);
        data.SaveChanges();

        return def.ShortName;
        //return Json(new[] { product }.ToDataSourceResult(request, ModelState));


    } 

parameter product have null values i have tested using parameter string product even but then api does not make a call i tries to pass string values but still then api fails to call?

I would pass it as a JSON string from the HTML using JQuery or AJAX call to the server.

Then, In my controller, I will use the post method as :

[HttpPost]
public string SaveDefCompny(string serializeddata)
{
   DefCompanyDTO product = NewtonSoft.JsonConvert.DeSerializeObject(serializeddata);
}

I use AJAX binding for the scenario as specified by Telerik in their demo:

public ActionResult Products_Create([DataSourceRequest]DataSourceRequest request, ProductViewModel product)
{
    if (ModelState.IsValid)
    {
        using (var northwind = new NorthwindEntities())
        {
            // Create a new Product entity and set its properties from the posted ProductViewModel
            var entity = new Product
            {
                ProductName = product.ProductName,
                UnitsInStock = product.UnitsInStock
            };
            // Add the entity
            northwind.Products.Add(entity);
            // Insert the entity in the database
            northwind.SaveChanges();
            // Get the ProductID generated by the database
            product.ProductID = entity.ProductID;
        }
    }
    // Return the inserted product. The grid needs the generated ProductID. Also return any validation errors.
    return Json(new[] { product }.ToDataSourceResult(request, ModelState));
}

you can learn more in the Telerik demo .

Since you mentioned in your comment that your data is coming from WebAPI, this example might help you as well.

UPDATE ( source ):

If you are using the MVC wrapper of the Kendo Grid this would not happen. There the grid is configured to make POST requests because of this ASP.NET MVC behavior. Make sure you have included kendo.aspnetmvc.min.js though. More info can be found in the docs .

By default Kendo Grid for ASP.NET MVC should make POST requests when configured for ajax binding. This is implemented by a custom DataSource transport and schema. Those are defined in the kendo.aspnetmvc.min.js. Make sure that this file is included after the other Kendo JavaScript files. More info can be found in the introduction help topic.

Solution: Correct Order Of JavaScript Files

 <script src="/Scripts/kendo.web.min.js"></script> <-- or kendo.all.min.js --> <script src="/Scripts/kendo.aspnetmvc.min.js"></script> 

Also see the Troubleshooting guide of Telerik .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM