所以我试图在控制器上制作表,这是我输入的代码
DataTable table = new DataTable();
Table.Columns.Add("Nama", typeof(string));
Table.Columns.Add("Nama2", typeof(string));
Table.Rows.Add("Manama", "Jeff");
Table.Rows.Add("Damn", "Daniel");
ViewData["Test"] = Table;
@ViewData["Test"] // when i type this it doesnt show anything on new page when i run it
答案 0 :(得分:1)
您遇到的问题是@ViewData["Test"]
隐式调用ToString()
对象到DataTable
对象,该对象将返回System.Data.DataTable
的标准名称而不是其内容(行和列) )。如果要从中创建表,则应创建HTML <table>
结构,如下所示:
@using System.Data
@{
var table = ViewData["Test"] as DataTable;
}
<table>
<thead>
<tr>
@foreach (DataColumn col in table.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in table.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
或者最好将DataTable
直接传递给模型:
控制器操作
DataTable table = new DataTable();
table.Columns.Add("Nama", typeof(string));
table.Columns.Add("Nama2", typeof(string));
table.Rows.Add("Manama", "Jeff");
table.Rows.Add("Damn", "Daniel");
return View(table);
查看
@using System.Data
<table>
<thead>
<tr>
@foreach (DataColumn col in Model.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach (DataRow row in Model.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
This fiddle包含在线示例,说明如何在视图页面内创建表。
相关问题: