Browse products by category

Select a category:

Product name Category
Product 121 Shoes
Product 124 Shoes
Product 125 Shoes
Product 128 Shoes
Product 129 Shoes
Product 132 Shoes
Product 133 Shoes
Product 136 Shoes
Product 137 Shoes
Product 140 Shoes
«1...34567891011...2627» Displaying 61 - 70 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);
}