Browse products by category

Select a category:

Product name Category
Product 41 Shoes
Product 44 Shoes
Product 45 Shoes
Product 48 Shoes
Product 49 Shoes
Product 52 Shoes
Product 53 Shoes
Product 56 Shoes
Product 57 Shoes
Product 60 Shoes
«12345678910...2627» Displaying 21 - 30 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);
}