2017-01-11 29 views
0

我想將Kendo網格一般用作局部視圖。劍道要求要麼定義的類型或數據表來實例化電網在Razor視圖通用Kendo MVC網格與不同型號一起使用

@(Html.Kendo().Grid<object>() or @(Html.Kendo().Grid(dataTable) 

我的問題是我想使用的任何對象,而不是特定的一個網格。

@(Html.Kendo().Grid<object>() 
    .Name(Model.MetricName) 
    .Resizable(resizing => resizing.Columns(true)) 
    .Reorderable(reorder => reorder.Columns(true)) 
    .Sortable(sorting => sorting.Enabled(true)) 
    .Pageable(pager => pager.PageSizes(new int[] { 10, 15, 20, 50 })) 
    .ColumnMenu() 
    .DataSource(dataSource => dataSource 
      .Ajax() 
      .Read(read => read.Action(Model.MetricName, "AdHocReport", new { metricId = Model.MetricId })) 
    ) 

) 

通過使用對象我能夠動態加載從ajax .read方法返回的數據。然而問題出在日期上。它們以JSON格式返回。

我用盡這種方法,我仍然獲得日期

Kendo ASP.NET MVC helper Grid generic class

有沒有辦法從類型的字符串表示定義格類型的JSON字符串表示?所以我們可以說我在viewModel上有一個字符串屬性,它是網格的類型。我怎麼說網格?使用反射來實例化類型

香港專業教育學院嘗試,但我得到了臭名昭著的「您使用的是像一個類型的變量」

這是我逼瘋......任何和所有幫助將不勝感激

+0

只怕劍道電網和它的MVC包裝沒有被設計爲。你必須做一些像[this](http://www.telerik.com/support/code-library/binding-to-datatable-0191a594e359) – mrmashal

回答

0

所以我找到了使這個工作和綁定正確的方式,正如上面提到的我的mrmashal它必須做與使用dataTables。

@(Html.Kendo().Grid(Model.GridTable) 

這裏是視圖模型屬性

public DataTable GridTable { get; set; } 

爲了使這個充滿活力的我使用反射來定義基於我想

Type elementType = Type.GetType(className, true); 
var properties = elementType.GetProperties(); 

DataTable dataTable = new DataTable(); 
foreach (PropertyInfo info in properties) 
    { 
     dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType)); 
    } 
viewModel.GridTable = dataTable; 
填充網格類的屬性數據表

但是,關鍵是確保從AJAX讀取返回的數據是dataTable,而不是IEnummerable類型。

DataTable dataTable = ToDataTable<AssetLocationHistoryMetricData>(metricData); 

var result = dataTable.ToDataSourceResult(request); 

,這是我用過的列表轉換爲一個DataTable

public static DataTable ToDataTable<T>(IEnumerable<T> items) 
    { 
     DataTable dataTable = new DataTable(typeof(T).Name); 

     //Get all the properties 
     PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 
     foreach (PropertyInfo prop in Props) 
     { 
      //Setting column names as Property names 
      dataTable.Columns.Add(prop.Name); 
     } 
     foreach (T item in items) 
     { 
      var values = new object[Props.Length]; 
      for (int i = 0; i < Props.Length; i++) 
      { 
       //inserting property values to datatable rows 
       values[i] = Props[i].GetValue(item, null); 
      } 
      dataTable.Rows.Add(values); 
     } 
     //put a breakpoint here and check datatable 
     return dataTable; 
    } 
相關問題