Holi Sale. Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Browse Tutorials

02 Intermediate

WebGrid with custom paging and sorting in ASP.NET MVC

WebGrid with custom paging and sorting in ASP.NET MVC

05 Mar 2024
Intermediate
195K Views
3 min read

WebGrid is simply used to display the data with paging and sorting. If you want to control the default behavior of the webgrid, you need do it manually. In this article, I would like to explore how can we do custom paging and sorting. In this article I have used the MVC4 and Entity Framework 5.0 with VS2012. Refer the article Enhancing WebGrid with ajax in MVC4 for more help.

How to do it...

The Model

First of all design the customer model using Entity Framework database first approach as show below;

Now develop the logic for querying the data from customer table and also develop the logic for custom paging and sorting.

public class ModelServices : IDisposable
{
 private readonly TestDBEntities entities = new TestDBEntities();
 
 //For Custom Paging
 public IEnumerable<Customer> GetCustomerPage(int pageNumber, int pageSize, string sort, bool Dir)
 {
 if (pageNumber < 1)
 pageNumber = 1;
 
 if (sort == "name")
 return entities.Customers.OrderByWithDirection(x => x.Name, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 else if (sort == "address")
 return entities.Customers.OrderByWithDirection(x => x.Address, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 else if (sort == "contactno")
 return entities.Customers.OrderByWithDirection(x => x.ContactNo, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 else
 return entities.Customers.OrderByWithDirection(x => x.CustID, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 }
 public int CountCustomer()
 {
 return entities.Customers.Count();
 }
 
 public void Dispose()
 {
 entities.Dispose();
 }
}

public class PagedCustomerModel
{
 public int TotalRows { get; set; }
 public IEnumerable<Customer> Customer { get; set; }
 public int PageSize { get; set; }
}

Extension Method for OrderByWithDirection

public static class SortExtension
{
 public static IOrderedEnumerable OrderByWithDirection
 (this IEnumerable source,Func keySelector,bool descending)
 {
 return descending ? source.OrderByDescending(keySelector)
 : source.OrderBy(keySelector);
 }
 
 public static IOrderedQueryable OrderByWithDirection
 (this IQueryable source,Expression> keySelector,bool descending)
 {
 return descending ? source.OrderByDescending(keySelector)
 : source.OrderBy(keySelector);
 }
}

The View

Now design the view based on the above developed model as show below

@model Mvc4_CustomWebGrid.Models.PagedCustomerModel
@{
 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("CustID",header: "ID", canSort: false),
 grid.Column("Name"),
 grid.Column("Address"),
 grid.Column("ContactNo",header: "Contact No")
 }
)

The Controller

Now, let's see how to write the code for implementing the webgrid functionality using model class and methods.

public class HomeController : Controller
{
 ModelServices mobjModel = new ModelServices();
 
 public ActionResult WebGridCustomPaging(int page = 1, string sort = "custid", string sortDir = "ASC")
 {
 const int pageSize = 5;
 var totalRows = mobjModel.CountCustomer();
 
 bool Dir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? true : false;
 
 var customer = mobjModel.GetCustomerPage(page, pageSize, sort, Dir);
 var data = new PagedCustomerModel()
 {
 TotalRows = totalRows,
 PageSize = pageSize,
 Customer = customer
 };
 return View(data);
 }
}

How it works..

What do you think?

I hope you will enjoy the tricks while programming with MVC Razor. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this