views:

1358

answers:

2

Hello, 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??

+5  A: 

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);
  }
}
%>
andymeadows
This is good for answering his question, but i don't recommend passing DataTables (or Entities) to the view, because it tightly couples the view with the technology used to get data out of the database. Its better to use POCO objects in my opinion.
Roberto Sebestyen
It's not called ViewState in MVC, it's called ViewData. And I agree with Roberto, you should be passing objects that contain the data you need from your controller to your view. Don't pass just a DataTable.
BFree
Yeah. Typo on my part. And I agree with Roberto. I've been fighting with an older inherited app and Viewstate is on my mind. Fixing the code/comment now.
andymeadows
+2  A: 

If I understand your question correctly, just because you are using MVC you do not have to use Entity framework to communicate with the database.

Inside your controller you can use whatever means you want to get the data out of the database. Then you can either transform that data into a custom object which you pass to your View, or you could potentially just pass a DataTable to your view.

Your view just has to know how to iterate through your object that you pass to it.

However, I recommend using POCO objects to pass to your view, so that you don't tightly couple your view data to the technology used to extract information from the database.

Roberto Sebestyen
What is this POCO object? Plain old CLR Object?ok,but then I wonder how to make a datatable into a POCO object
Josh
Hi Johsh. You are right POCO = Plain Old CLR object. You don't need to "make" your database into POCO. You can use any way to get your data such as a DataTable, or even Entity Framework. But after getting the data you would translate it into your own POCO object. Think of your POCO object as the "vehicle" for your data. Your View can then be tightly coupled to this, so it will not be too hard to change out the Data Access Layer without recoding a whole bunch of Views.
Roberto Sebestyen