网格不是使用Ajax绑定的
本文关键字:Ajax 绑定 网格 | 更新日期: 2023-09-27 17:50:27
我正在对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;
}
Kendo 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; }
}
My Grid正在调用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}]
但是网格是空的。
我使用相同的网格与服务器绑定,它工作得很好。
您需要返回DataSourceResult作为JsonResult来正确格式化Json。
[HttpGet]
public JsonResult GetRaceCarsAjax([DataSourceRequest]DataSourceRequest request)
{
var myRaceCars = GetRaceCars();
return Json(myRaceCars.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
附加建议-如果你从数据库中查询一些东西,确保ToDataSourceResult(request)执行你的查询,这将提高你的性能。
例如: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;
}