Kendo DataSource How to define a Model.Id when using DataTable

Kelly Cline picture Kelly Cline · Sep 10, 2013 · Viewed 16.7k times · Source

When defining a DataSource within @(Html.Kendo().Grid(Model), I have successfully used

.DataSource( dataSource => .Ajax( ).Model( model => model.Id( m => m.PROPERTY ) ) )

where PROPERTY is a property of the object that is the model. What is the correct syntax for defining Model.Id if the Model is a System.Data.DataTable and the Id column in the DataTable is TableId?

In other words, model.Id( m => ??? ).

I have tried, model.Id( m => Model.PrimaryKey ), which seems to satisfy the requirement that model.Id be set, but the Update Action (.Update(update => update.Action("MyUpdateMethod", "MyController")) doesn't ever hit, so I think there must still be something wrong.

Answer

Bryan Hobbs picture Bryan Hobbs · Sep 17, 2013

You can bind to a DataTable. In fact, we do a lot of dynamic grids and DataTable is our only recourse. Binding is a little different, though.

A snippet for one of ours is like this:

@model System.Data.DataTable
@(Html.Kendo().Grid(Model)
    .Name("SomeGrid")
    .Columns(columns=>
      { 
          foreach(System.Data.DataColumn column in Model.Columns)
          {
              columns.Bound(column.ColumnName).Title(column.Caption).Width(200);
          }
       }
    )
    .Selectable(selectable=>selectable
       .Type(GridSelectionType.Row)
    )
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model =>
             {
                 foreach(System.Data.DataColumn column in Model.Columns)
                 { 
                     model.Field(column.ColumnName,column.DataType);
                 }
             }
         )
         .Read(read=>Action("SomeMethod", "SomeController"))
         .PageSize(20)
     )