1

I have seen this question on how to display a DataTable in a view but was wondering if Html.Display or Html.DisplayFor could be made to work with a DataTable?

NB:

Use of DataTable is required for this project.

Community
  • 1
  • 1
Jon
  • 38,814
  • 81
  • 233
  • 382

2 Answers2

1

I created a DisplayTemplate by creating a partial view under my View folder in a folder called DisplayTemplates. I called the partial view Table. The model it uses is a datatable and below is the code. In your view you can then do @Html.DisplayForModel("Table")

@using System.Data;
@model DataTable
<table id="example" class="display">
    <thead>
        <tr>
            @{
                foreach (DataColumn col in Model.Columns)
                {
                <th>@col.ColumnName
                </th>
                }
            }
        </tr>
    </thead>
    <tbody>
        @{
            foreach (DataRow row in Model.Rows)
            {
            <tr>
                @{foreach (DataColumn col in Model.Columns)
                  {
                    <td>@row[col]
                    </td>
                  }
                }
            </tr>
            }
        }
    </tbody>
</table>
Jon
  • 38,814
  • 81
  • 233
  • 382
0

If you mapped your data table into an IEnumerable of an object, I believe DisplayFor would handle this.

Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Yup agree but I have to use a DataTable as I don't know what the properties will be for the object. – Jon Feb 08 '11 at 11:17
  • In Typed Datasets, DataTable is already IEnumerable. In other cases you can use `mydatatable.AsEnumerable()`. An item of IEnumerable is a DataRow (or inherited in case of Typed Datasets), so it depends if DataRow is already supported by Html.Display/Html.DisplayFor, or you should implement it. – Genius Feb 08 '11 at 12:41
  • I'm wondering if a custom DisplayTemplate might work but not sure how to implement it really. – Jon Feb 08 '11 at 13:00