问题
I am running a dynamically built SQL statement and putting the results in a datatable. I then need to display these results as a table in a partial view. I would normally create a List<> object and strongly type it to the page, but in this case I do not know what the final sql will be, since it is built by the user at run time.
So, how can I display the data in a datatable when I do not know what is in it? Also is there a better way to do this than in a datatable?
Thanks
回答1:
As you are displaying tablular data, you should use an html table to do the job. Dismissile's answer only displays one column of the table. The more generic answer can be found in the following SO question:
Displaying standard DataTables in MVC
The bit that concerns you is, with the model strongly typed as a DataTable:
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%: col.Caption %></th>
<%} %>
</tr>
</thead>
<tbody>
<% foreach(System.Data.DataRow row in Model.Rows) { %>
<tr>
<% foreach (var cell in row.ItemArray) {%>
<td><%: cell.ToString() %></td>
<%} %>
</tr>
<%} %>
</tbody>
</table>
EDIT
Edited to encode the content of the datable. As using mvc 2 (according to the tag), then Html.Encode not required, just the <%: notation that is available in mvc 2.
来源:https://stackoverflow.com/questions/4015025/how-do-i-display-a-datatable-in-asp-net-mvc-2