Here is the view code:
@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>
This is the controller code :
{
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);
I am following a tutorial and struck on the sorting part where it keeps showing this error,
i need your help to get remove the error and please explain whats going on the Sortlink helper method, i wan’t able to understand it well. The person who wrote this tutorial didn’t explain much on this part.
I’m guessing the problem is that you’re trying to use
ViewBag.isAscin the view, but never assigned it. Also, after the case statement, you’re resetting theproductsvariable, which completely invalidates the ordering you set up in the case statement– remove that. So after it should look like this: