C# – DataTable instead of Entity framework in Asp.Net MVC

asp.net-mvccdatatable

How do I use Datatable instead of Entity framework in Asp.Net mvc?

I'm referring to this tutorial on the asp.net Website ….
http://www.asp.net/Learn/mvc/tutorial-21-cs.aspx
….Can I return a datatable instead of a movie or movielist object??

Best Answer

You can return whatever you want provided it can be stored (serialized) in the ViewData. There is nothing "magic" about ASP.NET MVC that constrains values and/or types.

If you want to iterate over the DataTable in the view, put it in ViewData in the controller, retrieve it in the View, and iterate over it as you would anywhere else.

DataTable is serializable.

So something similar to the following should work:

<%
var tbl = ViewData["MyDataTable"];

foreach (DataRow row in tbl.Rows)
{
  foreach (DataColumn col in tbl.Columns)
  {
    Response.Write(row[col] as string ?? string.Empty);
  }
}
%>