Monday, July 7, 2014

MVC Ad-hoc DropDownList for PageSize

Example of Razor DropDown List for PageSize in an Index View using ViewBag.

Here is a controller
public class ProductController : Controller
  public ActionResult Index( int? page, int? pagesize )
    int pageSize = pagesize ?? 5;
    List<SelectListItem> items = new List<SelectListItem>{
      new SelectListItem{ Text="5", Value="5" },
      new SelectListItem{ Text="10", Value="10" }
    // items = List<SelectListItem>
    // "Value" = ValueText
    // "Text" = DisplayText
    // pagesize = SelectedListItem's Value from querystring
    ViewBag.PageSizeList = new SelectList( items, "Value", "Text", pagesize );
    ViewBag.CurrentPageSize = pageSize
Here is the view
@using PagedList
@using PagedList.Mvc
@model IEnumerable

<form id="form1" action=@Url.Action("Index", "Product") method="get">
  @Html.DropDownList( "pagesize", (SelectList)ViewBag.PageSizeList )
  // We keep DropDown list's name separate from ViewBag element's name

  @foreach ( var item in Model ) {  }

  @Html.PagedListPager( (IPagedList)Model, 
    page => Url.Action( "Index", new { page, pagesize = @ViewBag.CurrentPageSize })

<script type="text/javascript" src="">
<script type="text/javascript">
    // When onchange event occurs on <select id="pagesize">, 
    // simply submit the form, which will submit the new pagesize value as querystring.
    $('#pagesize').on('change', function(){


Me said...


Do you have a full example of that?

Cause the way you have it does not update when we select something from the dropdown.


K2 said...

Hi, I just updated the code on the View. I normally include all elements in a form and submit the entire form via javascript when onchange event occurs on the dropdown to update the page size.