我想计算数据库列的总数(金额),并将其显示在视图中总数标签旁边的标签上。我不确定如何执行此特定任务,应该使用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">
您可以在View中执行此操作,但是更好的方法是创建一个ViewModel,我给您一个基本的想法,您可以暂时在View中执行此操作:
@{
int totalAmount;
if(Model !=null)
{
totalAmount = Model.Sum(x=>x.Amount);
}
}
并在需要的地方以html显示它:
<h1>@totalAmount</h1>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句