Tengo una modelo en MVC.NET que contiene muchos registros, lo que causa que la vista de Index se haga muy larga. Cual es la forma correcta de poder paginalizar la vista que contenga botones de siguiente, anterior, etc.
1 respuesta
La forma mas simple que he visto es usando
@Html.PagedListPager()
puedes agregar el componente desde nuget
Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application
En el ejemplo PageList example veras
public class ProductController : Controller
{
public object Index(int? page)
{
var products = MyProductDataSource.FindAllProducts(); //returns IQueryable<Product> representing an unknown number of products. a thousand maybe?
var pageNumber = page ?? 1; // if no page was specified in the querystring, default to the first page (1)
var onePageOfProducts = products.ToPagedList(pageNumber, 25); // will only contain 25 products max because of the pageSize
ViewBag.OnePageOfProducts = onePageOfProducts;
return View();
}
}
que usa el ToPagedList()
Y en la view hace uso del @Html.PagedListPager
@{
ViewBag.Title = "Product Listing"
}
@using PagedList.Mvc; //import this so we get our HTML Helper
@using PagedList; //import this so we can cast our list to IPagedList (only necessary because ViewBag is dynamic)
<!-- import the included stylesheet for some (very basic) default styling -->
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
<!-- loop through each of your products and display it however you want. we're just printing the name here -->
<h2>List of Products</h2>
<ul>
@foreach(var product in ViewBag.OnePageOfProducts){
<li>@product.Name</li>
}
</ul>
<!-- output a paging control that lets the user navigation to the previous page, next page, etc -->
@Html.PagedListPager( (IPagedList)ViewBag.OnePageOfProducts, page => Url.Action("Index", new { page }) )