2011-06-14 74 views
0

我是使用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> 

可否请你指点我,这将是这样做

+4

我认为首选方法是将代码放入控制器或模型代码中,而不是视图。 – Zruty 2011-06-14 11:36:24

+0

我完全同意,我在控制器中有代码。 – PKK 2011-06-15 07:29:46

回答

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

我在这里得到了同样的问题:不能转换lambda表达式类型'字符串',因为它不是一个委托类型(我已经说过:使用System.Linq;) – PKK 2011-06-14 15:13:26

+0

这是AsEnumerable()丢失。该解决方案很好地工作。谢谢! – PKK 2011-06-15 07:29:19

+0

在我的情况下,我不得不使用Convert.ToInt32(o)而不是int.Parse(o) – PKK 2011-06-15 09:02:57

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

谢谢,我在尝试此代码时遇到以下错误:无法将lambda表达式转换为键入'string',因为它不是委托类型(我已经声明:使用System.Linq;) – PKK 2011-06-14 15:12:46

+1

你使用“System.Data.DataSetExtensions”吗?确保你使用了System.Data和System.Linq语句。你必须得到你的行“AsEnumerable”。本主题中的更多信息:http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/ad34a9f1-2849-478d-9405-b07a54b09aaf/ 检查史蒂文Killick后! – TrN 2011-06-15 06:48:56

+0

感谢这是AsEnumerable()失踪。 – PKK 2011-06-15 07:24:19