Grid没有使用Ajax绑定

时间:2015-05-21 16:33:35

标签: c# asp.net-mvc kendo-ui kendo-grid kendo-asp.net-mvc

我正在对Kendo MVC Grid进行一些简单的测试,而且我无法使用Ajax进行绑定。

这是我的代码:

我的控制器中的JSON调用:

[HttpGet]
public ActionResult GetRaceCarsAjax([DataSourceRequest]DataSourceRequest request)
{
    IList<RaceCar> myRaceCars = GetRaceCars();
    return Json(myRaceCars.AsQueryable(),JsonRequestBehavior.AllowGet);
}

protected IList<RaceCar> GetRaceCars(){
    IList<RaceCar> myCollection = new List<RaceCar>();
    var myEntity = new RaceCar
    {
        Color = "Red",
        Name = "Corvette",
        Count = 2
    };
    myCollection.Add(myEntity);
    // more cars inserted - 16 in all

    return myCollection;
}

剑道MVC声明:

@(Html.Kendo().Grid<RaceCar>() // Specify the type of the grid
    .Name("Grid")
    .AutoBind(true)
    .Columns(columns =>
    {
        columns.Bound(p => p.Name);
        columns.Bound(p => p.Color);
        columns.Bound(p => p.Count);
    })
    .Pageable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("GetRaceCarsAjax", "Grid").Type(HttpVerbs.Get)))
)

模特:

public class RaceCar
{
    public string Name { get; set; }
    public string Color { get; set; }
    public int Count { get; set; }
}

我的网格正在调用GetRaceCarsAjax并返回所有结果,如下所示:

[{"Name":"Corvette","Color":"Red","Count":2},{"Name":"Mini","Color":"Stars \u0026 Stripes","Count":1
},{"Name":"Masarati","Color":"Neon","Count":2},{"Name":"Lamborghini","Color":"Silver","Count":5},{"Name"
:"Miata","Color":"Black","Count":6},{"Name":"Sky","Color":"Blue","Count":1},{"Name":"TR7","Color":"Green"
,"Count":1},{"Name":"Dodge Charger","Color":"Yellow","Count":1},{"Name":"Gremlin","Color":"Fuschia","Count"
:0},{"Name":"Old Style Ford Taurus","Color":"Tan","Count":1},{"Name":"\u002767 Mustang","Color":"Matte
 Black","Count":1},{"Name":"Airplane","Color":"Invisible","Count":1},{"Name":"Chevy","Color":"Rusty"
,"Count":98},{"Name":"Jaguar","Color":"Red","Count":3},{"Name":"Aston Martin","Color":"Blue","Count"
:1},{"Name":"Porsche","Color":"Green","Count":8}]

但网格是空的。

我使用与服务器绑定相同的网格,它工作得很好。

1 个答案:

答案 0 :(得分:1)

您需要将DataSourceResult作为JsonResult返回,以正确格式化Json。

[HttpGet]
public JsonResult GetRaceCarsAjax([DataSourceRequest]DataSourceRequest request)
{
    var myRaceCars = GetRaceCars();
    return Json(myRaceCars.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

其他建议 - 如果您从数据库中查询某些内容,请确保ToDataSourceResult(请求)执行您的查询,这将提高您的性能。

例如:

protected IQueryable<RaceCar> GetRaceCars() 
{
    IQueryable<RaceCar> myCollection = null;

    using (var entity = new MyEntities())
    {
        myCollection = entity.RaceCar.Where(w => w.Something == "something"); // This doesn't call the database yet
    }
    return myCollection;
}