You're probably going to want to use
the WebGrid helper[
^]:
WebGrid in ASP.NET MVC4[
^]
WebGrid in ASP.NET MVC[
^]
The Ultimate Cookbook for the ASP.NET MVC WebGrid | DanylkoWeb[
^]
Unfortunately, you'll need to define the columns, since the
WebGrid
doesn't seem to be able to auto-generate columns for a
DataTable
or
DataView
. But it's not too difficult:
var columns = new List<WebGridColumn>(dtData.Columns.Count);
foreach (DataColumn column in dtData.Columns)
{
columns.Add(new WebGridColumn
{
ColumnName = column.ColumnName,
Header = column.Caption,
});
}
ViewBag.Columns = columns;
return View(dtData);
Then, in your view:
@model DataTable
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml(columns: ViewBag.Columns)
Alternatively, you could convert your
DataTable
to a list of dynamic objects, as described in
this StackOverflow answer[
^].
var model = new List<dynamic>(dtData.Rows.Count);
foreach (DataRow row in dtData.Rows)
{
var obj = (IDictionary<string, object>)new ExpandoObject();
foreach (DataColumn col in dtData.Columns)
{
obj.Add(col.ColumnName, row[col]);
}
model.Add(obj);
}
return View(model);
Then, in your view:
@model IList<dynamic>
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml()