这是我的第一个ASP.NET核心项目。我有一个单页面应用程序,我在Index.cshtml页面中有一个搜索框和一个按钮。如果搜索框文本为空,则不显示任何内容,否则将检索与pId相对应的记录并显示在Index.cshtml页面中。到目前为止,这样做效果很好。
我希望通过聚合给定日期的权重并将其显示在顶部来扩展此视图。因此,一旦用户输入PId并提交页面,我想显示
pId total_weight create_dt
在它下面,将是我已经拥有的当前视图
pId bIdc rule_id weight create_dt
我不确定我应该在哪里汇总分数?如何更新当前视图以显示聚合值?
控制器
public IActionResult Index(string pId)
{
var scores = from ts in _context.Scores
select ts;
if (!string.IsNullOrEmpty(pId))
{
scores = scores.Where(p => p.p_id.Equals(pId)).OrderByDescending(p => p.create_dt);
return View(scores.ToList());
}
else
return View();
}
Index.cshtml
<div id="p-form">
<form asp-controller="Score" asp-action="Index" method="get">
<p>
<b> P Id:</b> <input type="text" name="pId">
<input type="submit" value="Submit" />
</p>
</form>
</div>
@if (Model != null)
{
<div id="p-scores">
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.p_id)
</th>
<th>
@Html.DisplayNameFor(model => model.b_idc)
</th>
<th>
@Html.DisplayNameFor(model => model.rule_id)
</th>
<th>
@Html.DisplayNameFor(model => model.weight)
</th>
<th>
@Html.DisplayNameFor(model => model.create_dt)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(model => item.p_id)
</td>
<td>
@Html.DisplayFor(model => item.b_idc)
</td>
<td>
@Html.DisplayFor(model => item.rule_id)
</td>
<td>
@Html.DisplayFor(model => item.weight)
</td>
<td>
@Html.DisplayFor(model => item.create_dt)
</td>
</tr>
}
</tbody>
</table>
</div>
}
答案 0 :(得分:1)
您可以使用GroupBy方法对数据进行分组。
我会创建一个新类来表示分组数据
public class WeightItemTotal
{
public int PId { set; get; }
public decimal TotalWeight { set; get; }
public DateTime CreatedDate { set; get; }
}
现在,当您获得数据时,首先按照PId分组,对于每个项目(每个PId),根据日期对结果进行分组,并使用Sum方法获得总重量。
var resultGrouped = new List<WeightItemTotal>();
var pgrouped = _context.Scores.Where(c=>c.p_id==pId)
.GroupBy(a => a.PId);
foreach (var p in pgrouped)
{
var grouped = p.GroupBy(f => f.CreatedDate, items => items, (key, val)
=> new WeightItemTotal
{
PId = val.FirstOrDefault().PId,
CreatedDate = key,
TotalWeight = val.Sum(g => g.Weight)
}).ToList();
resultGrouped.AddRange(grouped);
}
return View(resultGrouped);
现在,由于我们将分组结果返回给视图,因此请确保它强类型为该类型
@model IEnumerable<WeightItemIotal>
<table>
@foreach(var p in Model)
{
<tr>
<td>@p.PId</td>
<td>@p.TotalWeight</td>
<td>@p.CreatedDate</td>
</tr>
}
</table>