Reputation: 14204
My controller is querying a database. The results are returned in a DataTable
. I want to display each DataRow
of the DataTable
in my view
. In my controller
, I have the following:
DataTable results = QueryDatabase();
ViewBag.Results = results;
I'm using RAZOR
syntax in my ASP.NET
MVC
view
. However, I'm not sure how to iterate through the rows and render each record. What is the recommended approach for doing this kind of task?
Upvotes: 1
Views: 1301
Reputation: 7757
You could use the Grid helper from the MvcContrib package. Then you can do something like
@Html.Grid(ViewBag.Results.Rows).Columns(column =>
{
column.For(r => r["column1"]);
column.For(r => r["column2"]);
...
})
That will generate all the table stuff for you you prefer not to hand-code the HTML.
Upvotes: 0
Reputation: 2669
First set the viewbag to rows instead of the table, so ViewBag.Results = results.Rows;
Then to iterate through the rows use:
@foreach(DataRow row in ViewBag.Results)
{
<div>@row["column_name"].ToString()</div>
}
Upvotes: 1