Browse products by category

Select a category:

Product name Category
Product 101 Shoes
Product 104 Shoes
Product 105 Shoes
Product 108 Shoes
Product 109 Shoes
Product 112 Shoes
Product 113 Shoes
Product 116 Shoes
Product 117 Shoes
Product 120 Shoes
«12345678910...2627» Displaying 51 - 60 of 263 item(s)

Razor code

@using MvcPaging.Demo.Models
@model IPagedList<Product>
@{
	ViewBag.Title = "Browse products by category";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("ViewByCategory", "Paging", FormMethod.Get))
{
	<p>
		Select a category:
		@Html.DropDownList("categoryName")
		<input type="submit" value="Browse" />
	</p>
}
@if (Model.Count() > 0)
{
	<table class="grid">
		<thead>
			<tr>
				<th>Product name</th>
				<th>Category</th>
			</tr>
		</thead>
		<tbody>
			@foreach (var product in Model)
			{
				<tr>
					<td>@product.Name</td>
					<td>@product.Category</td>
				</tr>
			}
		</tbody>
	</table>
	<div class="pager">
		@Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount).Options(o => o.AddRouteValue("categoryname", ViewBag.CategoryDisplayName))
		Displaying @Model.ItemStart - @Model.ItemEnd of @Model.TotalItemCount item(s)
	</div>
}

Controller code

public ActionResult ViewByCategory(string categoryName, int? page)
{
	categoryName = categoryName ?? this.allCategories[0];
	int currentPageIndex = page.HasValue ? page.Value - 1 : 0;

	var productsByCategory = this.allProducts.Where(p => p.Category.Equals(categoryName)).ToPagedList(currentPageIndex,
																										DefaultPageSize);
	ViewBag.CategoryName = new SelectList(this.allCategories, categoryName);
	ViewBag.CategoryDisplayName = categoryName;
	return View("ProductsByCategory", productsByCategory);
}