Enhancing WebGrid with ajax in MVC4

Enhancing WebGrid with ajax in MVC4

03 Jul 2024
Intermediate
5.14K Views
7 min read
Learn with an interactive course and practical hands-on labs

ASP.NET MVC with Web API Online Course - Learn & Certify

WebGrid with Ajax: An Overview

In previous posts, I have explained how can we do custom paging and sorting in WebGrid. You can also enhance WebGrid with Ajax for asynchronous updates of the webpage. In this MVC Tutorial, we will explore more about WebGrid with Ajax which will include Ajax paging and sorting, ajax web grid in mvc3 with custom paging and sorting, customized Ajax web grid in mvc4 mvc3, razor web grid template with AJAX. Consider our ASP.NET MVC Course for a better understanding of all MVC core concepts.

What is Ajax WebGrid?

For making an Ajax WebGrid, we have to set the value of ajaxUpdateContainerId parameter, in which we want to generate the WebGrid. Usually, the container should be a DIV as shown below:

 
WebGrid grid = new WebGrid(
 // Other code is removed for clarity
 ajaxUpdateContainerId: "container-grid"
 );

<div id="container-grid">@grid.GetHtml(
 fillEmptyRows: true,
 alternatingRowStyle: "alternative-row",
 headerStyle: "header-grid",
 footerStyle: "footer-grid",
 mode: WebGridPagerModes.All,
 ...
})</div>
 

We can also provide the id of the WebGrid to the ajaxUpdateContainerId parameter which is generated by the htmlAttributes of the GetHtml method as I am using in my example.

How to do it...

The Model

First of all, design the customer model using the Entity Framework database first approach as shown below

Now develop the logic for querying the data from the 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 shown below

 
@model Mvc4_CustomWebGrid.Models.PagedCustomerModel
@using Mvc4_CustomWebGrid.Models;
@{
 ViewBag.Title = "Ajax WebGrid with Custom Paging, Sorting";
}

<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>

@{
 WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize, defaultSort: "Name", ajaxUpdateContainerId: "grid");
 grid.Bind(Model.Customer, autoSortAndPage: false, rowCount: Model.TotalRows);
 grid.Pager(WebGridPagerModes.All);
 
 @grid.GetHtml(htmlAttributes: new { id = "grid" }, // id for ajaxUpdateContainerId parameter
 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..

Conclusion

So in this article, we have learned about Enhancing WebGrid with Ajax in MVC4 in asp.net mvc. I hope you enjoyed learning these concepts while programming with Asp.Net. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. Level up your career in MVC with our ASP.Net Core Certification.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

He is a renowned Speaker, Solution Architect, Mentor, and 10-time Microsoft MVP (2016–2025). With expertise in AI/ML, GenAI, System Design, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development, he bridges traditional frameworks with next-gen innovations.

He has trained 1 Lakh+ professionals across the globe, authored 45+ bestselling eBooks and 1000+ technical articles, and mentored 20+ free courses. As a corporate trainer for leading MNCs like IBM, Cognizant, and Dell, Shailendra continues to deliver world-class learning experiences through technology & AI.
Live Training - Book Free Demo
ASP.NET Core Certification Training
21 Sep
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this