Browse products by category

Select a category:

Product name Category
Product 1 Shoes
Product 4 Shoes
Product 5 Shoes
Product 8 Shoes
Product 9 Shoes
Product 12 Shoes
Product 13 Shoes
Product 16 Shoes
Product 17 Shoes
Product 20 Shoes
«12345678910...2627» Displaying 1 - 10 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);
}