How do I display a datatable in asp.net mvc 2?

与世无争的帅哥 提交于 2020-01-17 02:38:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!