如何使用MVVM剑道和C#从服务器端API调用剑道数据源的要求吗? [英] How to make Kendo Datasource request from server side API call using Kendo MVVM and c#?

查看:347
本文介绍了如何使用MVVM剑道和C#从服务器端API调用剑道数据源的要求吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的HTML页面作为前端,我要传递JSON数据到数据库的一排,我应该如何从服务器端传送一个列满值作为参数,以服务器端功能或要求数据源来填充实体?

下面是我的html code:

 < D​​IV ID =榜样>
    < D​​IV ID =kendoGrid
         数据角色=网格
         数据分页=真
         数据排序=真
         数据过滤=真
         数据工具栏=[创造,保存,取消]
         数据编辑=内联
         数据列=[      {'场':'ID','宽':100},
              {'场':'短名称','宽':100},
          {'场':'全名','宽':100},
       {'场':'ContactPerson','宽':100},
            {'场':'CurrentCurrency code','宽':100},
       {'场':'Adress1','宽':100},
       {'场':'CompanyCity','宽':100},
         {'场':'CompanyState','宽':100},
          {'场':'CompanyCountry','宽':100},
          {'场':'ZipPost code','宽':100},
      {'场':'TelArea','宽':100},
      {命令:'编辑','更新'],标题:操作,宽度:'250像素},     ]
         数据绑定=来源:产品
         风格=高度:500像素>< / DIV>
< / DIV>

下面是视图模型我的code,它的成功完全填充电网

  document.onreadystatechange =功能(){VAR视图模型= kendo.observable({    产品:新kendo.data.DataSource({        模式:{
            //数据:数据,
            总:计数,            型号:{
                ID:ID,
                字段:{
                    ID:{类型:INT},
                    短名称:{编辑:真的,键入:串},
                    全名:{编辑:真的,键入:串},
                    联系人:联系{编辑:真的,键入:串},
                    CurrentCurrency code:{编辑:真的,键入:INT},
                    Adress1:{编辑:真的,键入:串},
                    CompanyState:{编辑:真的,键入:串},                    CompanyCity:{编辑:真的,键入:串},
                    CompanyCountry:{编辑:真的,键入:串},
                    ZipPost code:{编辑:真的,键入:串},
                    TelArea:{编辑:真的,键入:串}                }
            }
        },
        批:真实,        运输: {            阅读:{
                网址:/ API /公司/ GetAllCompanies
                数据类型:JSON
            },
            创建: {
                输入:POST,
                //数据:{要求{} defcompny,键入:创造},
                网址:/ API /公司/ SaveDefCompny,//在这里你需要正确的API网址
                数据类型:JSON
                //的contentType:JSON
            },
            //更新:{
            // URL:/ API /公司/ SaveDefCompny,//在这里你需要正确的API网址
            //数据类型:JSON
            //},
            毁灭:{
                网址:/ API /公司/删除,//在这里你需要正确的API网址
                数据类型:JSON
            },
            parameterMap的:功能(数据,操作){                如果(!==操作读和放大器;&安培;数据){
                    调试器;
                    //返回kendo.stringify({defcompny:data.models [0]});
                    返回JSON.stringify({产品:data.models [0]});
                    //返回{defcompny:MYDATA};
                }
            }
        }    })
});
    // VAR的GridData = viewModel.product;    kendo.bind(的document.getElementById(榜样),视图模型);    }

下面是我的服务器端code,我现在用它的实体必须填入值当我拨打电话请求或如何使一个数据源请求来填充实体?

  [HttpPost]
    //产品必须对视图模型操作创建呼叫和发送产品数据的值,但它是空
    公共字符串SaveDefCompny(DefCompanyDTO产品)
    {        //返回defcompny.save();
        RPDBEntities数据=新RPDBEntities();
        VAR高清=新DefCompany();
        {
            def.Id = product.Id;
            def.CurrentCurrency code = product.CurrentCurrency code;
            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.ZipPost code = product.ZipPost code;
            def.TelArea = product.TelArea;
        }
        data.DefCompanies.Add(DEF);
        data.SaveChanges();        返回def.ShortName;
        //返回JSON(新[] {}产品.ToDataSourceResult(请求的ModelState));
    }

参数产品有我一直在使用参数字符串的产品甚至测试空值,但随后API不打个电话我试图通过字符串值,但仍然后API失败打电话?


解决方案

我想通过它从使用JQuery或AJAX调用服务器上的HTML一个 JSON 字符串。

然后,在我的控制器,我将使用POST方法如下:

  [HttpPost]
公共字符串SaveDefCompny(字符串serializeddata)
{
   DefCompanyDTO产品= NewtonSoft.JsonConvert.DeSerializeObject(serializeddata);
}

我用由Telerik的在他们的演示中指定AJAX的情况下结合:

 公众的ActionResult Products_Create([DataSourceRequest] DataSourceRequest要求,ProductViewModel产品)
{
    如果(ModelState.IsValid)
    {
        使用(VAR罗斯文=新NorthwindEntities())
        {
            //创建一个新的产品实体,并从发布的ProductViewModel设置其属性
            VAR实体=新产品
            {
                产品名称= product.ProductName,
                库存量= product.UnitsInStock
            };
            //添加实体
            northwind.Products.Add(实体);
            //插入实体在数据库中
            northwind.SaveChanges();
            //由数据库中获取所产生的产品ID
            product.ProductID = entity.ProductID;
        }
    }
    //返回插入的产品。网格需要生成的产品ID。也返回任何验证错误。
    返回JSON(新[] {}产品.ToDataSourceResult(请求的ModelState));
}

您可以了解更多的Telerik的演示

由于您在您的评论,你的数据是从未来的WebAPI,这个<一提到href=\"https://github.com/telerik/kendo-examples-asp-net/blob/0f8fe9e4a1eec1bfcdfce27965a812f824b4297f/grid-webapi-crud/Default.aspx\"相对=nofollow>例如可能会帮助你。

更新):

如果您使用的是剑道电网的MVC包装,这将不会发生。有网格被配置为使得正因为如此的ASP.NET MVC行为POST请求。请确保您已包括但kendo.aspnetmvc.min.js。更多信息可以在文档被发现。


  

在默认情况下剑道格为ASP.NET MVC应该POST请求时
  配置AJAX约束力。这是通过一个自定义实现的
  数据源的运输和架构。那些在所定义的
  kendo.aspnetmvc.min.js。请确保该文件后,包括
  其他剑道JavaScript文件。更多信息可以在找到
  引进的帮助主题。


  
  

解答:正确顺序的JavaScript文件

 &LT;脚本的src =/脚本/ kendo.web.min.js&GT;&LT; / SCRIPT&GT; &下;  - 或kendo.all.min.js  - &GT;
&LT;脚本的src =/脚本/ kendo.aspnetmvc.min.js&GT;&LT; / SCRIPT&GT;


另请参阅Telerik的的故障排除指南。

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.

这篇关于如何使用MVVM剑道和C#从服务器端API调用剑道数据源的要求吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆