You need to modify the route parameters of the PagedListPager()
method to include the vale of the sort order, for example
@Html.PagedListPager(Model, page => Url.Action("Products", new { OrderBy = ViewBag.SortOrder, page, pageSize = Model.PageSize }))
and then in the method, include
ViewBag.SortOrder = OrderBy;
before you return the view. However a better approach is to use a view model containing the properties used by the view which will resolve other issues with your code (for example, if you select the "Z-A"
option and submit the form, when you return it, the collection is sorted, but dropdown displays "-- Order By --"
indicating its not sorted. You view model should be
public class ProductsVM
{
[Display(Name = "Sort by:")]
public int? OrderBy { get; set; }
public IEnumerable<SelectListItem> OrderList { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
PagedList<Product> Products { get; set; }
}
and the controller method would be
[HttpGet]
public ActionResult Products(int? orderBy, int page=1, int pageSize=6)
{
private Shopping db = new Shopping();
IEnumerable<Product> products = db.Products; // not .ToList()
if (orderBy == 1)
{
products = products.OrderBy(p => p.Name);
}
else if (orderBy == 2)
{
products = products.OrderByDescending(p => p.Name)
}
ProductsVM model = new ProductsVM
{
OrderBy = orderBy,
OrderList = new List<SelectListItem>
{
new SelectListItem{ Text="A-Z", Value = "1" },
new SelectListItem{ Text="Z-A", Value = "2" }
},
Page = page,
PageSize = pageSize,
Products = new PagedList<Product>(products, page, pageSize);
};
return View(model);
}
And finally modify you view to use the view model
@model ProductsVM
....
@using (Html.BeginForm("Products", "Home", FormMethod.Get))
{
@Html.LabelFor(m => m.OrderBy)
@Html.DropDownListForFor(m => m.OrderBy, Model.OrderList, "-- Order By --")
<input type="submit" class="btn btn-default" value="Filter" />
}
@Html.PagedListPager(Model.Products, page => Url.Action("Products", new { orderBy = Model.OrderBy, page, pageSize = Model.PageSize }))
Showing @Model.Products.FirstItemOnPage to @Model.Products.LastItemOnPage of @Model.Products.TotalItemCount Products