Alex
Alex

Reputation: 49

How to loop through datatable and create table dynamically in ASP.Net MVC razor view?

I would like to make my razor code more dinamically. I have more than 100 columns with also more than 100 rows in the datatable (dr).

<table id="PS3" class="report">
<tr id="Parameter_name">
<td id="stick_no" bgcolor='#F0F0F0'>Stick No</td>
<td id="pos" bgcolor='#F0F0F0'>Pos</td>
<td id="id" bgcolor='#F0F0F0'>ID</td>
<td id="type" bgcolor='#F0F0F0'>Type</td>
<td id="packing_datetime" bgcolor='#F0F0F0'>Packing DateTime</td>
</tr>

@if (ViewData["AllEmpData"] != null)
{
    foreach (System.Data.DataRow dr in (ViewData["AllEmpData"] as System.Data.DataTable).Rows)
    {
        <tr>
            <td>
                @dr["stick_no"]
            </td>
            <td align="left">
                @dr["pos"]
            </td>
            <td>
                @dr["id"]
            </td>
            <td align="left">
                @dr["type"]
            </td>
            <td>
                @dr["packing_datetime"]
            </td>
        </tr>
    }
}
</table>

I would like to do something like this in the foreach cycle :

for(i=0; i< column_number; i++){
        <td>
            @dr[column_id[0].toString()]
        </td>
}

Where the column_number is the number of column in the id="Parameter_name" row. So in generally I don't want to write down all of the parameter in the foreach section.

Upvotes: 1

Views: 8743

Answers (1)

adiga
adiga

Reputation: 35253

You can use the Columns property of DataTable. like this:

<table id="PS3" class="report">
    <tr id="Parameter_name">
        <td id="stick_no" bgcolor='#F0F0F0'>Stick No</td>
        <td id="pos" bgcolor='#F0F0F0'>Pos</td>
        <td id="id" bgcolor='#F0F0F0'>ID</td>
        <td id="type" bgcolor='#F0F0F0'>Type</td>
        <td id="packing_datetime" bgcolor='#F0F0F0'>Packing DateTime</td>
    </tr>

    @if (ViewData["AllEmpData"] != null)
    {
        var dt = ViewData["AllEmpData"] as System.Data.DataTable;

        foreach (System.Data.DataRow dr in dt.Rows)
        {
            <tr>
                @foreach (System.Data.DataColumn col in dt.Columns)
                {
                    <td>@dr[col.ColumnName].ToString()</td>
                }
            </tr>
        }
    }
</table>

You can create the table headers this way as well. But you should consider converting the DataTable to a list in the controller and use it in the View.

Upvotes: 2

Related Questions