Displaying standard DataTables in MVC
This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:
Controller action:
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
DataTable dt = new DataTable("MyTable");
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
for (int i = 0; i < 3; i++)
{
DataRow row = dt.NewRow();
row["Col1"] = "col 1, row " + i;
row["Col2"] = "col 2, row " + i;
row["Col3"] = "col 3, row " + i;
dt.Rows.Add(row);
}
return View(dt); //passing the DataTable as my Model
}
View: (w/ Model strongly typed as System.Data.DataTable)
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%=col.Caption %></th>
<%} %>
</tr>
</thead>
<tbody>
<% foreach(System.Data.DataRow row in Model.Rows) { %>
<tr>
<% foreach (var cell in row.ItemArray) {%>
<td><%=cell.ToString() %></td>
<%} %>
</tr>
<%} %>
</tbody>
</table>
Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you should do things.
You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creating them.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.
I hope this helps!
How do I display a datatable in asp.net mvc 2?
As you are displaying tablular data, you should use an html table to do the job. Dismissile's answer only displays one column of the table. The more generic answer can be found in the following SO question:
Displaying standard DataTables in MVC
The bit that concerns you is, with the model strongly typed as a DataTable:
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%: col.Caption %></th>
<%} %>
</tr>
</thead>
<tbody>
<% foreach(System.Data.DataRow row in Model.Rows) { %>
<tr>
<% foreach (var cell in row.ItemArray) {%>
<td><%: cell.ToString() %></td>
<%} %>
</tr>
<%} %>
</tbody>
</table>
EDIT
Edited to encode the content of the datable. As using mvc 2 (according to the tag), then Html.Encode not required, just the <%: notation that is available in mvc 2.
Display Data from DataTable on ASP.net MVC 2
Try this
public ActionResult Index()
{
connection connect = new connection();
string query = "SELECT Event_Name FROM tbl_Event WHERE Event_ID=2";
return View(connect.SelectRecord(query));
}
internal DataTable SelectRecord(string query)
{
try
{
OpenConnection();
cmd = new SqlCommand(query, conn);
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd = null;
CloseConnection();
}
}
Here is view
View: (strongly typed as System.Data.DataTable)
<table border="1">
<thead>
<tr>
<%foreach (System.Data.DataColumn col in Model.Columns) { %>
<th><%=col.Event_Name%></th>
<%} %>
</tr>
</thead>
<tbody>
<% foreach(System.Data.DataRow row in Model.Rows) { %>
<tr>
<% foreach (var cell in row.ItemArray) {%>
<td><%=cell.ToString() %></td>
<%} %>
</tr>
<%} %>
</tbody>
Check this link : http://weblogs.asp.net/gunnarpeipman/archive/2011/11/19/asp-net-mvc-simple-view-to-display-contents-of-datatable.aspx
How can I pass DataReader/DataTable to view?
A view in mvc is always associated with a strongly typed model I.e a class..so in your case..just create a class with a list..while fetching data insert that data into a list and pass that class into the view..
class A {
public string name{get;set;}
public int age{get;set;}
}
//code when fetching data
//this list should be in the class where you fetch the data
Public list<A> list=new list<A>();
while(datareader.read)
{
A Aobj=new A();
String name=reader['name'].tostring();
int age =Convert.ToInt(reader['age']);
A.name=name;
A.age=age;
list.add(A);
}//end of while loop
//action resut
public ViewResult yourview(){
Return View(list);
}
//now you can access the data from the view.
By....
@model IEnumerable<A>
//here A is your class name
@foreach(var data in Model){
<div>@data.age</div>
}
Sorry for the code format... posted from mobile
Loading data in to a DataTable from a SQL Server database and displaying Charts in MVC3
I've found a solution that worked for me as far as the DataTable goes.
From the advice from Kevin in the comments section, I used a POCO model with an Entity Framework Code-First design.
Also research lead me to a great tutorial here -> http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-4
I based my model off this tutorial, then modified it a little to meet my needs.
Here is the model:
namespace Example_1.Models
{
public class Transaction
{
[Key]
public int TID { get; set; }
public DateTime TDate { get; set; }
public decimal TAmt { get; set; }
public string Trans_Type { get; set; }
public int MID { get; set; }
}
}
namespace Example_1.Models
{
public class Merchants
{
[Key]
public int MID { get; set; }
public string Merchant { get; set; }
public List<Transaction> Transactions { get; set; }
}
}
namespace Example_1.Models
{
public class SampleDBEntities : DbContext
{
public DbSet<Transaction> Transactions { get; set; }
public DbSet<Merchants> Merchants { get; set; }
}
}
The SampleDBEntities class must match the connection string in the web.config file. While the Transactions class and Merchants class must match the variables set up in my database.
Here is the controller:
public ActionResult Browse(string Merchant)
{
var mercmodel = sampledb.Merchants.Include("Transactions")
.SingleOrDefault(g => g.Merchant == Merchant);
return View(mercmodel);
}
The Merchant variable must match the path taken in your URL. For example my URL for this is
"http://localhost:64269/Transaction/Browse?Merchant=ISCO_CA"
Then in the view, I constructed a table where I passed my data into:
<script src="@Url.Content("~/Scripts/sorttable.js")" type="text/javascript"> </script>
@model Example_1.Models.Merchants
@{
ViewBag.Title = "Browse";
}
<h2>Browse</h2>
<h3>Transactions: @Model.Merchant</h3>
<table class="sortable">
<tr>
<th>ID</th>
<th>Date</th>
<th>Merchant</th>
<th>Amount</th>
</tr>
@foreach (var transaction in Model.Transactions)
{
<tr>
<td>
@transaction.TID
</td>
<td>
@transaction.TDate
</td>
<td>
@transaction.Trans_Type
</td>
<td>
$@transaction.TAmt
</td>
</tr>
}
</table>
This displays a beautiful table that looks like this:
Related Topics
How to Get a Property Value Using Reflection
Trying to Insert Datetime.Now into Date/Time Field Gives "Data Type Mismatch" Error
Create SQLite Database and Table
Visual Studio 2015 Not Syntax Highlighting Razor Nor Intellisense
Send a File to the Recycle Bin
How to Make Method Call Another One in Classes
Asp .Net MVC Disable Client Side Validation at Per-Field Level
Enumerate Windows Like Alt-Tab Does
Why Do I Need a Memory Barrier
How to Get the Lowercase Name of an Object, Even When Null, in C#
Programmatically Add New Column to Datagridview
In Wpf Can You Filter a Collectionviewsource Without Code Behind
How to Add an Event to a Usercontrol in C#
Write to Windows Application Event Log Without Event Source Registration