Rich

Thursday, October 14, 2010

[C# Asp.net MVC2] Paging with MVC Contrib

In a MVC application may need to page the results, or maybe the result of a query returns several hundred results, and we want to do on the web page view 10 per page and navigate between pages.
It is not a complicated thing, indeed, is very simple, whether done by "our code, or by using third-party libraries. one of these libraries is MVC Contrib.
In this post I will talk about the MVC Contrib, a project to add functionality and ease of use the Microsoft ASP.NET MVC Framework, which is useful for developers looking to develop and test the user interface elements, particularly through the use of MVC Contrib Grid, "Grid" for paging.
Then, download the library, includiamola in the project, and in our controller we call the namespace you need:


using MvcContrib.Pagination;
using MvcContrib.UI.Grid;
using MvcContrib;
using MvcContrib.UI.Pager;

Imagine having to see a list of Customer objects, retrieved from a repository, defined as:

public class Customer
{
   public int Id { get; set; }
   public string Surname { get; set; }
   public string Forename {get; set; }
   public DateTime DateOfBirth { get; set; }
}

In the controller :

public class CustomerController : Controller 
{
   private CustomerRepository _customRep = new CustomerRepository();

    public ActionResult Index(int? page)
   {
     var pagedCustomers = _customRep.FindAll().AsPagination(page ?? 1, 10);
     return View(pagedCustomers);
   }

View on the other hand, we import the namespaces you will need:

<%@ Import Namespace="MvcContrib.UI.Grid" %>
<%@ Import Namespace="MvcContrib.UI.Grid.ActionSyntax" %>
<%@ Import Namespace="MvcContrib.Pagination"%>
<%@ import Namespace="MvcContrib.UI.Pager" %>

 and build the grid:

<%= Html.Grid(Model).Columns(column => {
  column.For(cust => cust.Id).Named("Custome ID").DoNotEncode();
  column.For(cust => cust.Surname).Named("Surname").DoNotEncode();
  column.For(cust => cust.DateOfBirth).Named("Date Of Birth").DoNotEncode();
}) %>

<%= Html.Pager((IPagination)Model) %>


This is just a litle example as a page that shows a simple visualization of results, naturalemnte can be inserted into the "columns" of not only data but other things like ActionLink, for example:

column.For(cust => Html.ActionLink(cust.Id, "Details", new { id = cust.Id })).Named("Customer ID").DoNotEncode();

instead of showing only the id, creates a link to ActionResult "Details" passing the customer id as a parameter;

or, we assume that the customer has an additional property called "Photo" is inserted where the address of a picture:


column.For(cust => Html.ActionLinkPhoto(cust.Id, cust.Photo, "Details", new { id = cust.Id })).Named("Customer ID").DoNotEncode();

where ActionLinkPhoto Helper is a class in action specially written for a link where instead of having a "written", you have an image.

No comments:

Post a Comment

Program PTC...earning reading advertise