aparna rai
aparna rai

Reputation: 833

How to show Sum of Columns in MVC

I'm new in asp.net mvc and My problem is, I want to add footer for show the sum of the column .

Controller

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

View

<tbody>
    @foreach (var item in Model)
    {
        <tr>

            <td style="padding-left: 12px;">@Html.DisplayFor(modelItem => item.TicketNo)</td>
            <td style="padding-left: 12px; display: none;">@Html.DisplayFor(modelItem => item.name)</td>
            <td style="padding-left: 12px;">@Html.DisplayFor(modelItem => item.ArrDate)</td>
            <td style="padding-left: 12px;">@Html.DisplayFor(modelItem => item.quantity)</td>
            <td style="padding-left: 12px;">@Html.DisplayFor(modelItem => item.Total)</td>
            <td>@Html.DisplayFor(modelItem => item.Refund)</td>
            <td>@Html.DisplayFor(modelItem => item.TotalAmount)</td>
           </tr>
     }
</tbody>

I Want to Show Sum Of TotalAmount in Last of The List

Upvotes: 2

Views: 6026

Answers (2)

Wei Lin
Wei Lin

Reputation: 3811

c# code:

ViewBag.TotalAmount = ds.Tables[0].Select().Sum(w=> (int) w["RefundAmount"] );
  • ds is your dataset object
  • (int) w["RefundAmount"] use your type and prop

html :

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

Hope it helps you :)

Upvotes: 3

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

Just add one more <tr> element after the loop and use the Sum method to get the total.

Upvotes: 2

Related Questions