Kendo、mvc4 ヘルパーを使用してグリッド サーバー ページングを行う方法

StackOverflow https://stackoverflow.com//questions/12714872

  •  13-12-2019
  •  | 
  •  

質問

私はmvc4を使用しています。私のページの 1 つに Kendo Grid があります。1 ページに 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 を使用すると、すべてが機能します。ただし、そのページに必要な行だけをクエリするのではなく、すべての行をクエリします。

役に立ちましたか?

解決

データソース方式。だからあなたは次のようなものが必要になるでしょう:

@(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))
.

あなたはより多くの情報を見つけることができます 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"
    }
};

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");
        }
    }

type, serverSorting そして serverPaging ページングと並べ替えがサーバー側で確実に行われるようにするために重要です。 type しなければならない なれ aspnetmvc-ajax, そうでない場合、クエリ データは、Read メソッドの [DataSourceRequest] 属性で指定されたモデル バインダーによって認識されません。kendo dataSource によって送信されたクエリ データを解析するための独自のカスタム モデルバインダーを作成する場合を除き、この属性を省略することはできません。このモデルバインダーは、ASP.NET MVC の DefaultModelBinder で使用されるモデルバインディング規則に準拠していません。

ASP.NET MVCのKendo UIを使用している場合は、もう一方の回答が機能します。あなたが自分でページングを実装する必要があるならば。Kendo DataSourceは、リクエストを行うときにPageSizeと現在のページを送信します。ページングを実行するためにそれを使用することができます。また、物事をさらに簡単にする(Hint Linq)。

エラー 「LINQからエンティティへの方法は、メソッドのSystem.String ToString() 'メソッドを認識しません。このメソッドはストア式に翻訳できません。 "} これを中心にGatするには、自明ですが、

のようなことをするべきです。
return Product.**AsEnumerable**.Select(p => new ProductVM()
        {
            Name = p.Name,
            ProductionYear= p.ProductionYear.Year.ToString()
            Id = p.Id });
.

ASENUMERABLEを使用すると、DBからのすべてのレコードをもたらします。フィルタリングの後に使用するのに最適です。

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

でむしろ Products.Asenumerable.where(X=> X.ACTIVE= TRUE)

剣道の例をダウンロードしてから、解凍してフォローする ASP.NET MVC Q1 <your directory>\Kendo UI2013\wrappers\aspnetmvc\Examples\Areas\razor\Views\web\grid\ ビューインデックスの場合 そして ASP.NET MVC Q1 <your directory>\Kendo UI2013\wrappers\aspnetmvc\Examples\Controllers IndexController

の場合

あなたのビューでは、避けるために.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);
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top