总结MVC中的表

时间:2011-06-14 11:32:19

标签: c# asp.net-mvc

我是使用MVC的新手,我对在表格中汇总行数据有疑问。

一些背景知识:

首先,我使用普通的SQL语句收集大量数据。我使用DataTable来存储数据。然后我用普通的HTML表输出数据。这非常好用,我没有问题。

我现在想总结每一行的所有值,并在底行显示结果。

我知道我可以在数据层中完成此操作。循环遍历数据表并将行的值汇总到一个新行。然后最后将“摘要行”作为最后一行附加。

一些代码:

    <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>

请您告诉我哪种方式最好/最简单

2 个答案:

答案 0 :(得分:1)

在ControllerAction中进行计算。像这样......

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);
}

答案 1 :(得分:1)

您应该考虑是否要将数据“打包”到模型(类)中。在模型部分的mvc项目中添加类:

public class YourModel
{
 public string Name
 public int NrOfRows
 public YourModel(string name, int nrOfRows) 
 {
  Name = name;
  NrOfRows = nrOfRows;
 }
}

然后在您的控制器方法中执行:

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();
}

然后你去看法:

<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>
相关问题