HI WELCOME TO SIRIS

Enhancing WebGrid with ajax in MVC4




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:
  1. WebGrid grid = new WebGrid(
  2. // Other code is removed for clarity
  3. ajaxUpdateContainerId: "container-grid"
  4. );
  5.  
  6. <div id="container-grid">@grid.GetHtml(
  7. fillEmptyRows: true,
  8. alternatingRowStyle: "alternative-row",
  9. headerStyle: "header-grid",
  10. footerStyle: "footer-grid",
  11. mode: WebGridPagerModes.All,
  12. ...
  13. })</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.
  1. public class ModelServices : IDisposable
  2. {
  3. private readonly TestDBEntities entities = new TestDBEntities();
  4. //For Custom Paging
  5. public IEnumerable<Customer> GetCustomerPage(int pageNumber, int pageSize, string sort, bool Dir)
  6. {
  7. if (pageNumber < 1)
  8. pageNumber = 1;
  9. if (sort == "name")
  10. return entities.Customers.OrderByWithDirection(x => x.Name, Dir)
  11. .Skip((pageNumber - 1) * pageSize)
  12. .Take(pageSize)
  13. .ToList();
  14. else if (sort == "address")
  15. return entities.Customers.OrderByWithDirection(x => x.Address, Dir)
  16. .Skip((pageNumber - 1) * pageSize)
  17. .Take(pageSize)
  18. .ToList();
  19. else if (sort == "contactno")
  20. return entities.Customers.OrderByWithDirection(x => x.ContactNo, Dir)
  21. .Skip((pageNumber - 1) * pageSize)
  22. .Take(pageSize)
  23. .ToList();
  24. else
  25. return entities.Customers.OrderByWithDirection(x => x.CustID, Dir)
  26. .Skip((pageNumber - 1) * pageSize)
  27. .Take(pageSize)
  28. .ToList();
  29. }
  30. public int CountCustomer()
  31. {
  32. return entities.Customers.Count();
  33. }
  34. public void Dispose()
  35. {
  36. entities.Dispose();
  37. }
  38. }
  39.  
  40. public class PagedCustomerModel
  41. {
  42. public int TotalRows { get; set; }
  43. public IEnumerable<Customer> Customer { get; set; }
  44. public int PageSize { get; set; }
  45. }

Extension Method for OrderByWithDirection

  1. public static class SortExtension
  2. {
  3. public static IOrderedEnumerable OrderByWithDirection
  4. (this IEnumerable source,Func keySelector,bool descending)
  5. {
  6. return descending ? source.OrderByDescending(keySelector)
  7. : source.OrderBy(keySelector);
  8. }
  9. public static IOrderedQueryable OrderByWithDirection
  10. (this IQueryable source,Expression> keySelector,bool descending)
  11. {
  12. return descending ? source.OrderByDescending(keySelector)
  13. : source.OrderBy(keySelector);
  14. }
  15. }

The View

Now design the view based on the above developed model as show below
  1. @model Mvc4_CustomWebGrid.Models.PagedCustomerModel
  2. @using Mvc4_CustomWebGrid.Models;
  3. @{
  4. ViewBag.Title = "Ajax WebGrid with Custom Paging, Sorting";
  5. }
  6.  
  7. <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
  8.  
  9. @{
  10. WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize, defaultSort: "Name", ajaxUpdateContainerId: "grid");
  11. grid.Bind(Model.Customer, autoSortAndPage: false, rowCount: Model.TotalRows);
  12. grid.Pager(WebGridPagerModes.All);
  13. @grid.GetHtml(htmlAttributes: new { id = "grid" }, // id for ajaxUpdateContainerId parameter
  14. fillEmptyRows: false,
  15. alternatingRowStyle: "alternate-row",
  16. headerStyle: "grid-header",
  17. footerStyle: "grid-footer",
  18. mode: WebGridPagerModes.All,
  19. firstText: "<< First",
  20. previousText: "< Prev",
  21. nextText: "Next >",
  22. lastText: "Last >>",
  23. columns: new[] {
  24. grid.Column("CustID",header: "ID", canSort: false),
  25. grid.Column("Name"),
  26. grid.Column("Address"),
  27. grid.Column("ContactNo",header: "Contact No")
  28. })
  29. }

The Controller

Now, let's see how to write the code for implementing the webgrid functionality using model class and methods.
  1. public class HomeController : Controller
  2. {
  3. ModelServices mobjModel = new ModelServices();
  4. public ActionResult WebGridCustomPaging(int page = 1, string sort = "custid", string sortDir = "ASC")
  5. {
  6. const int pageSize = 5;
  7. var totalRows = mobjModel.CountCustomer();
  8. bool Dir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? true : false;
  9. var customer = mobjModel.GetCustomerPage(page, pageSize, sort, Dir);
  10. var data = new PagedCustomerModel()
  11. {
  12. TotalRows = totalRows,
  13. PageSize = pageSize,
  14. Customer = customer
  15. };
  16. return View(data);
  17. }
  18. }

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.