views:

71

answers:

1

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  A: 

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:

http://stackoverflow.com/questions/2243898/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.

awrigley