Browse products by category

Select a category:

Product name Category
Product 501 Shoes
Product 504 Shoes
Product 505 Shoes
Product 508 Shoes
Product 509 Shoes
Product 512 Shoes
Product 513 Shoes
Product 516 Shoes
Product 517 Shoes
Product 520 Shoes
«12...18192021222324252627» Displaying 251 - 260 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);
}