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.


Leave a Reply

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