How to bind JSON to Kendo Grid datadource in MVC

4.5k views Asked by At

I'm trying to dynamically bind the JSON response to grid. I have set autobind = false so I can control when to call ReadData().

I have a simplified example below that I can't get to work.

In the view(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>   
}

In the controller i have

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

Using the developer tools in chrome I can see that the response for the ReadData() is [{"Name":"Abc","Age":10},{"Name":"PersonName","Age":25}] however the rendered grid is only showing the column names but no data columns.

MyModel is a simple class :

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

There are 1 answers

0
dimodi On BEST ANSWER

The Kendo UI MVC Grid is designed to work with ToDataSourceResult() in the action method that serves the data. Check the following article:

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

ToDataSourceResult() will take care of performing the data operations (sorting, paging, etc), and will also serve the data in the expected format, which is:

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

(Spaces were added for readability, the important part is the presence of Data and Total.)

Edit addition: To add to this answer, an example of what your controller code may look like is as follows:

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