如何对数据库的一列求和并通过 asp.net mvc 中的标签显示它

本文关键字:net asp mvc 显示 标签 求和 数据库 一列 | 更新日期: 2023-09-27 18:36:50

我想计算 db 列(金额)的总计,并将其显示在视图中总标签旁边的标签上。我不确定如何执行这个特定的任务,它应该在 Javascript 中完成吗?或者我可以使用哪些其他方法?这是我的项目...

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

指数

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

索引视图

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

如何对数据库的一列求和并通过 asp.net mvc 中的标签显示它

您可以在View中执行此操作,但更好的方法是创建一个ViewModel,我为您提供了如何暂时在View中执行此操作的基本概念:

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

并在您想要的任何位置以 HTML 形式向下显示它:

<h1>@totalAmount</h1>

您似乎正在将捐赠列表传递给剃刀视图,因此您应该能够对模型等集合使用扩展方法。总和(x=> x.金额)在显示屏内。