Sunday, April 13, 2014

Paging & Sorting in MVC 4 with Grid.

1:Create model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
    public class ProModel
    {
        public int TotalRows { get; set; }
        public IEnumerable<TblCustomer> Customer { get; set; }
        public int PageSize { get; set; }
    }
    public class ModelServices : IDisposable
    {
        private readonly tst_dbEntities entities = new tst_dbEntities();

        public IEnumerable<TblCustomer> GetCustomerPage(int pageNumber, int pageSize, string sort, bool Dir)
        {
            if (pageNumber < 1)
                pageNumber = 1;

            if (sort == "name")
                return entities.TblCustomers.OrderByDescending(x => x.Customername)
                .Skip((pageNumber - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            else
                return entities.TblCustomers.OrderBy(x => x.CustomerId)
                .Skip((pageNumber - 1) * pageSize)
                .Take(pageSize)
                .ToList();
        }
        public int CountCustomer()
        {
            return entities.TblCustomers.Count();
        }

        public void Dispose()
        {
            entities.Dispose();
        }
    }
    public static class SortExtension
    {

    }
}

2:Create Controller

 public class HomeController : Controller
    {
        ModelServices mobjModel = new ModelServices();

        public ActionResult WebGridCustomPaging(int page = 1, string sort = "custid", string sortDir = "ASC")
        {
            const int pageSize = 3;
            var totalRows = mobjModel.CountCustomer();

            bool Dir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? true : false;

            var customer = mobjModel.GetCustomerPage(page, pageSize, sort, Dir);
            var data = new ProModel()
            {
                TotalRows = totalRows,
                PageSize = pageSize,
                Customer = customer
            };
            return View(data);
        }
}

3:Create View
@model MvcApplication1.Models.ProModel
@{
 ViewBag.Title = "WebGrid with Custom Paging, Sorting";
 WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
 grid.Bind(Model.Customer,
 autoSortAndPage: false,
 rowCount: Model.TotalRows); 
}
 
@grid.GetHtml(
 fillEmptyRows: false,
 alternatingRowStyle: "alternate-row",
 headerStyle: "grid-header",
 footerStyle: "grid-footer",
 mode: WebGridPagerModes.All,
 firstText: "<< First",
 previousText: "< Prev",
 nextText: "Next >",
 lastText: "Last >>",
 columns: new[] {
 grid.Column("CustomerId",header: "ID", canSort: false),
 grid.Column("Customername"),
 grid.Column("Address"),
 grid.Column("City",header: "City")
 }
)

No comments:

Post a Comment