我有两个表连接在一起并返回搜索结果视图。查询中的记录格式如下:
degreeid schoolid seqno coursename
1 1 1 A
1 1 1 B
1 1 2 C
1 1 3 D
我需要用相同的seqno计算课程。如何在剃刀视图foreach循环或控制器中实现它?我可以创建一个函数来返回控制器中的计数,但是如何从剃刀视图中调用此计数函数?
public class HomeController : Controller
{
private CourseDataModel db = new CourseDataModel();
ActionResult Index()
{
using (CourseDataModel db = new CourseDataModel())
{
var searchResults = (from a in TableA
join b in TableB on
new { subject=a.subject, catalog=a.catalog } equals
new { subject=b.Subject, catalog=b.Catalogno } into ab
orderby a.seqno
from b in ab.DefaultIfEmpty()
select new JoinModel
{
Courselist = a,
Contentsummary = b
}
).ToList();
if (searchResults == null) { return Content("No record found"); }
return View(searchResults);
}
}
我的index.cshtml代码如下:
@model IEnumerable<course.Models.JoinModel>
@if (Model != null)
{
if (Model.Count() != 0)
{
<table >
<tbody>
<tr>
<th class="column1" scope="col">Degree ID</th>
<th class="column2" scope="col">Course</th>
<th class="column3" scope="col">Count</th>
</tr>
@foreach (var item in Model)
{
<!-- display class="new-sequence" when degree_seqno changes-->
<tr >
<td class="column1">
@Html.DisplayFor(modelItem => item.Courselist.degreeno)
</td>
<td class="column2">
@Html.DisplayFor(modelItem => item.Courselist.coursename)
</td>
<td> @* here I want to display a count of the same seqno *@
</td>
</tr>
}
</tbody>
</table>
答案 0 :(得分:0)
如何按IGrouping
分组,那么您可以计算每个group ab by ab.seqno into seqNoGrps
@foreach(var grp in Model)
{
<tr><td>@grp.Key</td></tr>
@foreach(var joinModel in grp)
{
<tr>
<td class="column1">
@Html.DisplayFor(modelItem => item.Courselist.degreeno)
</td>
<td class="column2">
@Html.DisplayFor(modelItem => item.Courselist.coursename)
</td>
<td> @* here I want to display a count of the same seqno *@
@grp.Count()
</td>
</tr>
}
}
然后在您的视图中迭代每个组
SELECT main.NBHD, main.PARID, main.PRICE, main.SALEDT, main.SALEVAL
FROM
(SELECT t.NBHD, t.PARID, t.PRICE, t.SALEDT, t.SALEVAL,
(SELECT COUNT(*) FROM mytable sub
WHERE sub.NBHD = t.NBHD
AND sub.SALEDT >= t.SALEDT) AS rank
FROM mytable t) AS main
WHERE main.rank <= 40
ORDER NBHD, PARID, SALEDT DESC
答案 1 :(得分:0)
试试这个
foreach (var group in Model.GroupBy(item => item.seqno))
{
foreach (var item in group)
{
<tr>
<td class="column1">
@Html.DisplayFor(modelItem => item.degreeno)
</td>
<td class="column2">
@Html.DisplayFor(modelItem => item.coursename)
</td>
<td>
@group.Count()
</td>
</tr>
}
}