如何使用绑定到DataTable的Kendo Grid进行排序

时间:2014-04-24 20:42:10

标签: c# asp.net-mvc-4 sorting datatable kendo-grid

我在尝试实现Kendo Grid控件的排序功能时遇到困难。当我单击一列来对值进行排序时,它会将我带到404页面。我所看到的文档都没有将网格绑定到DataTable,我也想知道是否需要对排序进行特定的操作。有人可以帮忙吗?

查看代码:

    @{
        if (IsPost && Request.Url.AbsolutePath.Contains("Carriers"))
        {
                @(Html.Kendo().Grid((DataTable)(ViewData["CarrierResults"]))
                    .Name("carrierSearchResults")
                    .Sortable()
                )
        }
    }

控制器代码:

    [HttpPost]
    public ActionResult Carriers()
    {
        DealerPortalRepository dpr = new DealerPortalRepository();
        // The SearchForCarriers method below returns a DataTable
        ViewData["CarrierResults"] = dpr.SearchForCarriers();  
        return View("~/Views/Search/Index.cshtml");
    }

编辑:查询代码:

    public DataTable SearchForCarriers()
    {
        var query = from a in db.Affiliates
                    where a.AffiliateLevel == 1
                    select new { a.AffiliateName };
        return createCarrierTable(query);
    }

    public DataTable createCarrierTable(IEnumerable<dynamic> query)
    {
        // Create new DataTable since the query above does not produce a DataRow that follows a schema already defined in the database.
        DataTable dt = new DataTable();
        dt.Columns.Add(
            new DataColumn()
            {
                DataType = System.Type.GetType("System.String"),
                ColumnName = "Affiliate Name"
            }
        );

        // Add the row(s) to the DataTable.
        foreach (dynamic item in query)
        {
            var row = dt.NewRow();
            row["Affiliate Name"] = item.AffiliateName;
            dt.Rows.Add(row);
        }

        return dt;
    }

P.S。我知道我应该使用模型而不是ViewData,但我最初并没有这样实现它,因为我的DataTable中的匿名类型让我失望。

1 个答案:

答案 0 :(得分:1)

由于我看不到你的其余代码,这是我的猜测。

您可以删除[HttpPost]并再次测试吗?

如果仍然不起作用,则需要另一个接受 DataSourceRequest 作为参数的操作方法。

public ActionResult Carriers_Read([DataSourceRequest]DataSourceRequest request)
{
  ...
}

请看Grid Ajax Binding