开发者

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

开发者 https://www.devze.com 2023-01-22 02:12 出处:网络
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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消