【问题标题】:How to bind JSON to Kendo Grid datadource in MVC如何在 MVC 中将 JSON 绑定到 Kendo Grid 数据源
【发布时间】:2016-12-21 11:00:06
【问题描述】:

我正在尝试将 JSON 响应动态绑定到网格。我已经设置了autobind = false,所以我可以控制何时调用ReadData()

下面有一个简化的示例,我无法开始工作。

在视图中(cshtml)

@(Html.Kendo().Grid<MyModel>()
    .Name("GridDetail")
    .AutoBind(false)
    .DataSource(ds =>
    {
        ds.Ajax().Read(r =>
        {
            r.Action("ReadData", "Home"); //action in Home controller
        });
    })
    .Columns(c =>
    {
        c.Bound(m => m.Name);
        c.Bound(m => m.Age);
    })
)

@section Scripts{
    <script type="text/javascript">
        $(function () {
            var grid = $("#GridDetail").data("kendoGrid");
            grid.dataSource.read();
        });

    </script>   
}

在我拥有的控制器中

public ActionResult ReadData()
{
    var model = new[]
    {
        new MyModel
        {
            Name = "Abc",
            Age = 10
        }, 
        new MyModel
        {
            Name = "PersonName",
            Age = 25
        }, 
    };
    return Json(model, JsonRequestBehavior.AllowGet);
}

使用 chrome 中的开发人员工具,我可以看到 ReadData() 的响应是 [{"Name":"Abc","Age":10},{"Name":"PersonName","Age":25}],但是呈现的网格仅显示列名,但没有显示数据列。

MyModel 是一个简单的类:

public class MyModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}

【问题讨论】:

    标签: kendo-ui telerik kendo-asp.net-mvc telerik-grid


    【解决方案1】:

    Kendo UI MVC Grid 设计为在提供数据的操作方法中与ToDataSourceResult() 一起使用。查看以下文章:

    http://docs.telerik.com/aspnet-mvc/helpers/grid/binding/ajax-binding

    ToDataSourceResult() 将负责执行数据操作(排序、分页等),还将以预期的格式提供数据,即:

    {
        Data: [
            { "Name": "Abc", "Age": 10 },
            { "Name": "PersonName", "Age": 25 }
        ],
        Total: 2
    }
    

    (为了可读性添加了空格,重要的部分是DataTotal的存在。)

    编辑添加:要添加到此答案,您的控制器代码可能如下所示的示例:

    public ActionResult ReadData([DataSourceRequest] DataSourceRequest request)
    {
        var model = new[]
        {
            new MyModel
            {
                Name = "Abc",
                Age = 10
            }, 
            new MyModel
            {
                Name = "PersonName",
                Age = 25
            }, 
        };
        return Json(model.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多