Reputation: 127
I'm new in using MVC and I have a question about summarizing the row data in a table.
Some background:
First I collect a lot of data with an ordinary SQL statement. I use a DataTable to store the data. Then I output the data with an ordinary HTML table. This works very nicely and I have no problems with it.
I would now like to summarize all of the values for each row and display the result in the bottom row.
I know that I could do this already in the data layer. Loop through the datatable and summarize the values for the rows into a new row. Then finally append the "summary row" as the last row.
Some code:
<tr class="header">
<th>Person</th>
<th>NrOfRows</th>
</tr>
<% foreach (System.Data.DataRow row in Model.Rows) { %>
<tr>
<td><%: row["Name"].ToString()%></td>
<td><%: row["NrOfRows"].ToString()%></td>
</tr>
Could you please advice me which would be the best/easiest way to do this
Upvotes: 0
Views: 1827
Reputation: 1352
Do the calculation in the ControllerAction. something like this...
public ActionResult Index()
{
var rows = this.repository.GetAll();
this.ViewData["total"] = rows.AsEnumerable().Select(o => o["NrOfRows"]).Select(o => int.Parse(o)).Sum();
return this.View(rows);
}
Upvotes: 1
Reputation: 1250
You should consider if you don't want to "pack" your data into a model (class). in mvc project in model section add class:
public class YourModel
{
public string Name
public int NrOfRows
public YourModel(string name, int nrOfRows)
{
Name = name;
NrOfRows = nrOfRows;
}
}
then in your controller method you do:
public ActionResult Summarize(/*parameters list*/)
{
var rows = (get data) //In here you assign here your table content
ViewData.Model = rows.Select(row => new YourModel(row["Name"], int.Parse(row["NrOfRows"])));
ViewData["nrRowCount"] = rows.Select(row => row.NrOfRows).Sum();
return View();
}
and you go to the view:
<table>
<th>Person</th>
<th>nrOfRows</th>
<%: foreach(var yourModel in Model) { :%>
<tr>
<td>yourModel.Name</td>
<td>yourModel.NrOfRows</td>
</tr>
<%: } :%>
<tr>
<td>Summary: </td>
<td> <%: ViewData["nrRowCount"] %:></td>
</tr>
</table>
Upvotes: 1