1
votes

I am working with Kendo+razor and I want to create a Kendo grid that does not have any specific data model (in my case, I have to show the results of a SQL query, entered by user, so the result can have any number/type of columns). To make it generic I tried to bind the grid to System.data.DataTable and an ajax call to populate that grid. It works fine when loaded for the first time, but when I repopulate the same grid, it does not update its column names.

Scenario:
Ajax call is made on a button click to populate grid with the query results. On first ajax call the result was a JSON with attributes id, name, and description. The grid showed correct data with the 3 above mentioned columns and 4 rows.
On the second ajax call the response JSON contains attributes UserName, UserType, Address, PhoneNumber, this time the grid does not update its model binding and columns remain the previous three columns id, name, and description but the number of rows gets updated with no data in it (as the columns are not present in the returned JSON)

I want to rebind the columns to the returned JSON attributes that can differ every time.

Here is my HTML code:

@model System.Data.DataTable
<div>
@(Html.Kendo().Grid(Model)
.Name("ResultsGrid") 
.TableHtmlAttributes(new { Class = "kendoGrid" })
)
</div>

and the Javascript on button click code:

function execute() {
 $.ajax({
 url: "something something",
 type: "GET",
 contentType: "application/json;charset=utf-8",
 data: "",
 dataType: "json",
 success: function (data) {
        $("#ResultsGrid").kendoGrid({
              scrollable: false,
              pageable: true,
              sortable: true,
              resizable: true,
              dataSource: {
                        data: data,
                        pageSize: 5
                    }
                });
 }
}

How can I refresh the grid to bind to columns to the new JSON attributes?

2

2 Answers

1
votes

You first need to destroy the old grid and then create a new one:

success: function(data) {
    // get reference to the grid instance
    var grid = $("#ResultsGrid").data("kendoGrid");
    // destroy it
    grid.destroy();
    $("#ResultsGrid")
        .empty() // clear the old HTML
        .kendoGrid( {
           dataSource: {
              data: data,
              pageSize: 5
           }
        });

}
0
votes
success: function(data) {
// get reference to the grid instance
var grid = $("#ResultsGrid").data("kendoGrid");
// destroy it
grid.destroy();
$("#ResultsGrid")
    .empty() // clear the old HTML
    .kendoGrid( {
       dataSource: {
          data: data,
          pageSize: 5
       }
    });

}