ASP.NET MVC: Simple view to display contents of DataTable

In one of my current projects I have to show reports based on SQL Server views. My code should be not aware of data it shows. It just asks data from view and displays it user. As WebGrid didn’t seem to work with DataTable (at least with no hocus-pocus) I wrote my own very simple view that shows contents of DataTable.

I don’t focus right now on data querying questions as this part of my simple generic reporting stuff is still under construction. If the final result is something good enough to share with wider audience I will blog about it for sure.

My view uses DataTable as model. It iterates through columns collection to get column names and then iterates through rows and writes out values of all columns. Nothing special, just simple generic view for DataTable.

@model System.Data.DataTable 
@
using
System.Data;

<h2>Report</h2>
 

<table>
 
   
<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.ColumnName]</td>
 
        }        
       
</tr>
 
    }    
   
</tbody> 
</table
>

In my controller action I have code like this. GetParams() is simple function that reads parameter values from form. This part of my simple reporting system is still under construction but as you can see it will be easy to use for UI developers.

public ActionResult TasksByProjectReport()
{
   
var data = _reportService.GetReportData("MEMOS"
, GetParams());
   
return View(data);
}

Before seeing next silver bullet in this example please calm down. It is just plain and simple stuff for simple needs. If you need advanced and powerful reporting system then better use existing components by some vendor.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    3 thoughts on “ASP.NET MVC: Simple view to display contents of DataTable

    • December 21, 2012 at 10:55 am
      Permalink

      should use “system.data.datacolumn”

    • January 3, 2013 at 11:55 pm
      Permalink

      Thanks for this post. Very helpful.

    • March 15, 2021 at 6:33 am
      Permalink

      Thank you!!!

    Leave a Reply

    Your email address will not be published. Required fields are marked *