如何在MVC中显示列的总和

时间:2018-04-28 05:42:59

标签: c# sql asp.net-mvc

我是asp.net mvc的新手,我的问题是,我想添加页脚以显示列的总和。

控制器

Sample Call to Google's geocode Web Service:

查看

List<GenerateTicket_Details> bk = new List<GenerateTicket_Details>();
con.Open();
string query = "";

query += @" select TicketNo,Name,ArrDate,sum(CostumeQuantity) As Quantity, sum(CostumeTotalPrice) As Total, sum(ISNULL(RefundAmount,0)) AS REFUND
 ,sum(ISNULL(CostumeTotalPrice,0) - ISNULL(RefundAmount,0)) AS TotalAmount from GenerateTicket where 1=1";
query += @"  Group by TicketNo,Name,ArrDate ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
da.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
    bk.Add(new GenerateTicket_Details() { TicketNo = dr[0].ToString(), name = dr[1].ToString(), ArrDate = dr[2].ToString(), quantity = dr[3].ToString(), Total = Convert.ToDecimal(dr[4].ToString()), Refund = Convert.ToDecimal(dr[5].ToString()), TotalAmount = Convert.ToDecimal(dr[6].ToString()) });
    string orderDetails = dr[3].ToString();

}
cmd.ExecuteNonQuery();
ViewBag.MyCustomCollection = bk;
return View(bk);

我希望在列表的最后部分显示 TotalAmount 的总和

2 个答案:

答案 0 :(得分:4)

c#c​​ode:

ViewBag.TotalAmount = ds.Tables[0].Select().Sum(w=> (int) w["RefundAmount"] );
  • ds是您的数据集对象
  • (int)w [&#34; RefundAmount&#34;]使用你的类型和道具

html:

<tbody>
    @foreach (var item in Model)
    {
.......
     }
<tr><td>TotalAmount : @ViewBag.TotalAmount</td></tr>
</tbody>

希望它可以帮助你:)

答案 1 :(得分:2)

只需在循环后添加一个<tr>元素,然后使用Sum方法获取总数。