这是查看代码:
@helper sortLink(string name, int id)
{
<a href="@Url.Action("Products", "Home", new { sortBy = id, isasc = (id == ViewBag.sortBy ? !@ViewBag.isAsc : @ViewBag.isAsc).ToString().ToLower() })">@name</a>
}
<h2 class="center">Products</h2>
<table class="Products">
@* header *@
<tr>
<th>@sortLink("ID",1)</th>
<th>@sortLink("Name",2)</th>
<th>@sortLink("Number", 3)</th>
<th>@sortLink("Color", 4)</th>
<th>@sortLink("Standard Cost", 5)</th>
<th>@sortLink("List Price", 6)</th>
<th>@sortLink("Size", 7)</th>
<th>@sortLink("Weight", 8)</th>
</tr>
这是控制器代码:
{
AdventureWorksLT2008R2Entities db = new AdventureWorksLT2008R2Entities();
const int pageSize = 10;
[HttpGet]
public ActionResult Products(int page = 1, int sortBy = 1, bool isAsc = true)
{
IEnumerable<Product> products;
#region sorting
switch (sortBy)
{
case 1:
products = isAsc ? db.Products.OrderBy(p => p.ProductID) : db.Products.OrderByDescending(p => p.ProductID);
break;
case 2:
products = isAsc ? db.Products.OrderBy(p => p.Name) : db.Products.OrderByDescending(p => p.Name);
break;
case 3:
products = isAsc ? db.Products.OrderBy(p => p.ProductNumber) : db.Products.OrderByDescending(p => p.ProductNumber);
break;
case 4:
products = isAsc ? db.Products.OrderBy(p => p.Color) : db.Products.OrderByDescending(p => p.Color);
break;
case 5:
products = isAsc ? db.Products.OrderBy(p => p.StandardCost) : db.Products.OrderByDescending(p => p.StandardCost);
break;
case 6:
products = isAsc ? db.Products.OrderBy(p => p.ListPrice) : db.Products.OrderByDescending(p => p.ListPrice);
break;
case 7:
products = isAsc ? db.Products.OrderBy(p => p.Size) : db.Products.OrderByDescending(p => p.Size);
break;
case 8:
products = isAsc ? db.Products.OrderBy(p => p.Weight) : db.Products.OrderByDescending(p => p.Weight);
break;
}
#endregion
products = db.Products
.OrderBy(p=>p.ProductID)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList();
ViewBag.CurrentPage = page;
ViewBag.PageSize = pageSize;
ViewBag.TotalPages = Math.Ceiling((double)db.Products.Count()/pageSize);
return View(products);
我正在关注一个教程,并在排序部分一直显示此错误,我需要您的帮助来删除错误,请解释 Sortlink 辅助方法发生了什么,我无法很好地理解它。编写本教程的人并没有对此部分进行太多解释。