Pages

Tuesday 1 April 2014

Displaying DataTable result on MVC4 view

To Display the Content of DataTable result into View add TataTable to ViewBag which is used to pass data from controller to view.

Controller Action:

Here I assigned the dt i.e. datatable result to viewbag. ViewBag.data=dt;

View Code:

Following code display display data on view. Here ViewBag.data.Rows is passed to foreach() then from each row I selected the column i.e. ViewBag.data.Columns by row wise.
/*First loop print column Header*/
<tr>
  <th>
      SL.No.
   </th>
  @foreach (var col in ViewBag.detailReportData.Columns)
 {
    <th id="gridHeader" style="white-space: nowrap;">
     @col
      </th>
  }
 </tr>
/*Second loop print each data row*/
 @foreach (System.Data.DataRow row in ViewBag.data.Rows)
        {   
                <tr>
                @foreach (System.Data.DataColumn col in ViewBag.data.Columns)
                {              
                    <td>
                        @row[col.ColumnName]
                    </td> 
                }
            </tr>
        }

No comments:

Post a Comment