Please enable Javascript to correctly display the contents on Dot Net Tricks!

Enhancing WebGrid with ajax in MVC4

Posted By : Shailendra Chauhan, 11 Jan 2013
Updated On : 11 Jun 2014
Total Views : 139,478   
Support : MVC4 & MVC3
 

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 update of webpage.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 show 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 htmlAttributes of GetHtml method as I am using in my example.

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
@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..

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.


 
Recommended for you
 
About the Author
Shailendra Chauhan

Shailendra Chauhan is an Entrepreneur, Author, Architect, and Corporate Trainer. He has rewarded as Microsoft MVP for his exceptional contributions in Microsoft Visual Studio and Development Technologies.

With more than 7 years in hand experience Shailendra Chauhan is a polymath in the domains of Microsoft .NET technologies and an array of other technologies including JavaScript, AngularJS, Node.js, Ionic and NoSQL Databases to name but a few.

He is the author of some of most popular e-books which encompass technical Interview on Node.js Interview Questions and Answers , ASP.NET MVC Interview Questions and Answers , AngularJS Interview Questions and Answers and LINQ Interview Questions and Answers. Furthermore he is a technical reviewer for book on ASP.NET MVC 4 Mobile App Development. Know more...
 
Free Interview Books
 
10 SEP
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN 05:00 PM-06:30 PM IST

More Details
7 SEP
ASP.NET MVC with AngularJS Development (online)

Weekdays (Mon-Fri) 07:30 AM-09:00 AM IST

More Details
3 SEP
ASP.NET MVC with AngularJS Development (online)

Weekend (Sat, Sun) 03:00 PM-05:00 PM IST

More Details
29 AUG
NodeJS Development (online)

MON-FRI     06:00 AM-07:30 AM IST

27 AUG
PPC Marketing (offline)

Sat, Sun     03:00 PM-05:00 PM IST

20 AUG
NodeJS Development (offline)

Sat, Sun     11:00 AM-12:30 PM IST

16 AUG
NodeJS Development (online)

Mon-Fri     09:00 PM-10:30 PM IST

12 AUG
ASP.NET MVC with AngularJS Development (online)

Mon-Fri     09:30 PM-11:00 PM IST

1 AUG
ASP.NET MVC with AngularJS Development (online)

Mon-Fri     07:30 AM-09:00 AM IST

24 JUL
AngularJS Development (offline)

Sat,Sun     08:00 AM-09:30 AM

24 JUL
ASP.NET MVC with AngularJS Development (offline)

Sat, Sun     09:30 AM-11:00 AM

14 JUL
PPC Marketing (offline)

Sat, Sun     12:00 AM-02:00 PM IST

11 MAY
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 
+