【问题标题】:Kendo, how to do Grid server paging using mvc4 helper剑道,如何使用 mvc4 助手进行网格服务器分页
【发布时间】:2012-10-03 18:48:17
【问题描述】:

我正在使用 mvc4。在我的一个页面上,它有 Kendo Grid。我想每页显示 5 行。但是,如果我使用的是 mvc 助手,我使用纯 javascript 来做这件事没有问题。我迷路了,在网上找不到任何样品。

这是我的 javascript 代码。

        <script language="javascript" type="text/javascript">

            $(document).ready(function () {
                $("#grid").kendoGrid({
                    dataSource: {
                        type: "json",
                        serverPaging: true,
                        pageSize: 5,
                        transport: { read: { url: "Products/GetAll", dataType: "json"} },
                        schema: { data: "Products", total: "TotalCount" }
                    },
                    height: 400,
                    pageable: true,
                    columns: [
                            { field: "ProductId", title: "ProductId" },
                            { field: "ProductType", title: "ProductType" },
                            { field: "Name", title: "Name" },
                            { field: "Created", title: "Created" }
                        ],
                    dataBound: function () {
                        this.expandRow(this.tbody.find("tr.k-master-row").first());
                    }
                });
            });

现在如果我使用 mvc 助手

            @(Html.Kendo().Grid(Model)
                .Name("Grid")  //please help me to finish the rest

更新

添加操作代码。

    [HttpPost]
    public ActionResult GetAll([DataSourceRequest]DataSourceRequest request, int id)
    {
        var products= ProductService.GetAll(id);

        return Json(products.ToDataSourceResult(request));
    }

服务层的GetAll方法:

    public IQueryable<Product> GetAll(int id)
    {
        var products= ProductRepository.Get(p => p.Id== id && p.IsActive == true, null, "ProductionYear")
                    .OrderBy(o => o.Name); //.ToList();

        return Product.Select(p => new ProductVM()
        {
            Name = p.Name,
            ProductionYear= p.ProductionYear.Year.ToString()
            Id = p.Id
        }).AsQueryable();
    }

现在,如果我运行该应用程序,我将收到以下错误:

“LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且该方法无法转换为存储表达式。”}

在GetAll 方法中,我注释掉了“ToList()”。如果我使用 ToList,一切正常。但我将查询所有行,而不是只查询该页面所需的那些行。

【问题讨论】:

    标签: asp.net-mvc kendo-ui


    【解决方案1】:

    您可以在DataSource method 中设置PageSize。所以你需要这样的东西:

    @(Html.Kendo().Grid(Model)
         .Name("Grid") 
         .DataSource(dataSource => dataSource.Ajax()
                                        .PageSize(5)
                                        .Read(c => c.Action("GetAll", "Products")
                                        .Model(s => s.Id(m => m.Id)))
         .Columns(columns =>
         {
            columns.Bound(m => m.ProductId).Title("ProductId");
            //other colums
         })
        .Events(g => g.DataBound("somefunction"))
        .Pageable(true))
    

    您可以在 KendoUI Grid 的Asp.NET MVC wrappers documentation 找到更多信息。

    【讨论】:

    • 也许我错了,但我认为 c.Action("GetAll", "Products") 将始终返回所有行。
    • 我刚刚拿走了你的 js 代码并变成了 Razor 助手系统税。我不知道您的“GetAll”方法是如何实现的。但是,如果您像 linked article 那样准备您的操作方法,例如使用ToDataSourceResult 方法,它将正确执行服务器端分页,并且只会返回 5 行。
    • 我更新了我的问题,请看一下,仍然无法正常工作
    • .PageSize() 与 .Server() 以及 .Ajax() 一起用于服务器绑定数据集。
    【解决方案2】:

    如果您使用 Kendo 的 ASP.NET MVC 包装器并且直接使用 Kendo JavaScript 对象并且您正在尝试进行服务器端分页,那么您需要如下创建数据源:

    var dataSource = {
        "type":"aspnetmvc-ajax",
        "serverSorting": true,
        "serverPaging": true,
        "page": 1,
        "pageSize": 8,
        "schema": {
          "data":"items",
          "total":"count",
          "errors":"errors"
        }
    };
    

    您的 Read 控制器方法将如下所示:

        public ActionResult List_Read([DataSourceRequest]DataSourceRequest request) {
            try {
                var model = null /* prepare your model object here contain one page of grid data */;
    
                // using Json.NET here to serialize the model to string matching the
                // schema expected by the data source
                var content = JsonConvert.SerializeObject(new { count = model.Count, items = model.Items }, Formatting.None);
    
                return Content(content, "application/json");
            }
            catch (Exception exception) {
                // log exception if you need to
    
                var content = JsonConvert.SerializeObject(new { errors = exception.Message.ToString() }, Formatting.None);
    
                return Content(content, "application/json");
            }
        }
    

    typeserverSortingserverPaging 对于确保分页和排序发生在服务器端很重要。 type 必须aspnetmvc-ajax,否则Read方法中[DataSourceRequest]属性指定的模型绑定器将无法识别查询数据。除非您想编写自己的自定义 modelbinder 来解析 kendo dataSource 发送的查询数据,否则不能省略该属性,这不符合 ASP.NET MVC 中 DefaultModelBinder 使用的模型绑定约定。

    【讨论】:

      【解决方案3】:

      如果您将 Kendo UI 用于 ASP.NET MVC,则另一个答案将起作用。如果不需要,则需要自己实现分页。 Kendo DataSource 将在发出请求时发送 pageSize 和当前页面。您可以使用它来进行分页。它还发送“take”和“skip”,让事情变得更容易(提示 Linq)。

      【讨论】:

      【解决方案4】:

      错误 “LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且此方法无法转换为存储表达式。”} 是不言自明的,要解决这个问题,你应该做类似的事情

      return Product.**AsEnumerable**.Select(p => new ProductVM()
              {
                  Name = p.Name,
                  ProductionYear= p.ProductionYear.Year.ToString()
                  Id = p.Id });
      

      使用 AsEnumerable 会带来数据库中的所有记录,因此最好在任何过滤后使用

      products.where(x => x.active = true).AsEnumerable
      

      而不是 products.AsEnumerable.where(x => x.active = true)

      【讨论】:

        【解决方案5】:

        下载剑道示例,然后解压并关注 &lt;your directory&gt;\Kendo UI 用于 ASP.NET MVC Q1 2013\wrappers\aspnetmvc\Examples\Areas\razor\Views\web\grid\ 对于视图索引 和 &lt;your directory&gt;\Kendo UI 用于 ASP.NET MVC Q1 2013\wrappers\aspnetmvc\Examples\Controllers 对于索引控制器

        在您看来,您可能还希望 .ServerOperation(true) 如下所示以避免 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了 maxJsonLength 属性上设置的值。 如果你有大数据要获取

        @(Html.Kendo().Grid(<yourmodel>)
            .Name("Grid")
            .Columns(columns =>
               ...
            })
        
                .Filterable()
                .Pageable()
        
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(8)
                    .ServerOperation(true) )
        
                    .Model(model =>
                    {
                        model.Id(p => p.Id);
                        ...
                    })
                )
            )
        

        也在控制器中的 ActionResult Products_Read 考虑

          DataSourceResult result = GetProducts().ToDataSourceResult(request,  o => new { Id = o.Id, ... } );
          return Json(result , JsonRequestBehavior.AllowGet);
        

        【讨论】:

          猜你喜欢
          • 2013-07-08
          • 1970-01-01
          • 2023-03-16
          • 1970-01-01
          • 1970-01-01
          • 2023-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多