如何累计数据库的列并通过asp.net mvc中的标签显示它?

时间:2016-03-01 14:02:05

标签: c# asp.net asp.net-mvc razor view

我想计算db列(Amount)的总和,并将其显示在视图中总标签旁边的标签上。如果在Javascript中完成,我不确定如何执行此特定任务?或者我可以使用其他什么方法? 这是我的项目......

MODEL

    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Web;

    namespace webassignment.Models
    {
        public class Donation
        {
            public int ID { get; set; }
            public string DisplayName{ get; set; }
            public DateTime Date { get; set; }
            public decimal Amount { get; set; }
            public decimal TaxBonus { get; set; }
            public string Comment { get; set; }

        }
        public class DonationDBContext: DbContext
        {
            public DbSet<Donation> Donation { get; set; }

        }
  }

INDEX

  // GET: Donations
    public ActionResult Index()
    {
        return View(db.Donation.ToList());
    }

INDEX VIEW

    <table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.DisplayName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Date)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Amount)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.TaxBonus)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Comment)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.DisplayName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Date)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Amount)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TaxBonus)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Comment)
        </td>
        <td>

        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}




</table>
<script type="text/javascript">

2 个答案:

答案 0 :(得分:1)

您可以在View中执行此操作,但更好的方法是创建ViewModel,我将基本了解如何在View中执行此操作:

@{

   int totalAmount;
   if(Model !=null)
   {
      totalAmount = Model.Sum(x=>x.Amount);
   } 
}

并在html中向下显示它你想要的地方:

<h1>@totalAmount</h1>

答案 1 :(得分:0)

您似乎正在向剃刀视图传递捐赠列表,因此您应该能够在显示中使用类似model.Sum(x =&gt; x.Amount)的集合的扩展方法。