user70192
user70192

Reputation: 14204

Displaying a list of items with a template in ASP.NET MVC

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

Answers (2)

luksan
luksan

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

felbus
felbus

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

Related Questions