Webgrid Paging, sorting and filtering in ASP.Net MVC

Today, In this tutorial I will show you webgrid Paging, sorting and filtering functionality in asp.net MVC application.

It is an essential approach to using paging, sorting and filtering technique in applications where a lot of data to be loaded from a database. So here in this article, I have tried to show how we can do this just following few simple steps.
Webgrid Paging, sorting and filtering in ASP.Net MVC
First Name Last Name Email City Country
asdf asdf asdf@asdf.asd asdf asdf
Dany Prastio da@gmail.com Bekasi Indonesia
lizzy m ccc@ccc.com hola hola
Ronny kuo Javed ronny@gmail.com MP India
sefa sefa sefa@sefa.com sefa sefa
Sourav Mondal souravmondal45@gmail.com Kolkata India
Sourav Mondal souravmondal45@gmail.com Kolkata India
Sourav Mondal souravmondal45@gmail.com Kolkata India
sravanthi kuo Mondal souravmondal45@gmail.com Kolkata India
Tony Roy1 tonyroy@gmail.com Los Angeles USA
Webgrid Paging, sorting and filtering in ASP.Net MVC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;

namespace WebgridPagingSortingFiltering.Controllers
{
    public class HomeController : Controller
    {
        
        public ActionResult Index(int page =1, string sort = "FirstName", string sortdir="asc", string search="")
        {
            int pageSize = 10;
            int totalRecord = 0;
            if (page < 1) page = 1;
            int skip = (page * pageSize) - pageSize;
            var data = GetEmployees(search, sort, sortdir, skip, pageSize, out totalRecord);
            ViewBag.TotalRows = totalRecord;
            ViewBag.search = search;
            return View(data);
        }

        public List<Employee> GetEmployees(string search, string sort, string sortdir, int skip, int pageSize, out int totalRecord)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = (from a in dc.Employees
                            where
                                    a.FirstName.Contains(search) ||
                                    a.LastName.Contains(search) ||
                                    a.EmailID.Contains(search) ||
                                    a.City.Contains(search) ||
                                    a.Country.Contains(search)
                            select a
                                );
                totalRecord = v.Count();
                v = v.OrderBy(sort + " " + sortdir);
                if (pageSize > 0)
                {
                    v = v.Skip(skip).Take(pageSize);
                }
                return v.ToList();
            }
        }
	}
}
Posted By :