剑道,如何使用 mvc4 助手进行网格服务器分页



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

这是我的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,一切正常。但是我将查询所有行,而不是仅查询该页面所需的那些行。

可以在数据源方法中设置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 网格的 Asp.NET MVC 包装器文档中找到更多信息。

如果您没有使用 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"
    }
};

读取控制器方法将如下所示:

    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] 属性指定的模型绑定器识别。除非要编写自己的自定义模型绑定器来分析由 kendo 数据源发送的查询数据,否则不能省略该属性,该数据源不符合 ASP.NET MVC 中的 DefaultModelBinder 使用的模型绑定约定。

如果您将剑道UI用于 ASP.NET MVC,则另一个答案将起作用。如果没有,则需要自己实现分页。Kendo 数据源将在发出请求时发送 pageSize 和当前页面。您可以使用它进行分页。它还发送"take"和"skip",这使得事情变得更加容易(提示Linq)。

错误"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

而不是然后 产品。AsEnumerable.where(x => x.active = true)

下载剑道示例,然后解压缩并按照 ASP.NET MVC Q1 2013wrappersaspnetmvcExamplesAreasrazorViewswebgrid<your directory>Kendo UI对于视图索引和 ASP.NET MVC Q1 2013wrappersaspnetmvcExamplesControllers<your directory>Kendo UI对于索引控制器

在您看来,您可能还需要 .服务器操作(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);
                ...
            })
        )
    )

也在操作结果的控制器中Products_Read考虑

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

最新更新