Filtering records in WebGrid using dropdownlist in MVC

MVC WebGrid

The blog entry demonstrates how you can filter the data on the basis of another control selection such as dropdown list.

The following example contains a dropdownlist with all department names and a webgrid that will contain employee’s details including their department that will be changed on the to dropdownlist selection change.

Here is the table ‘tbl_Employee‘:

EmployeeIdEmpnameAgeDepartment_idSalary
1David30125000.0000
2A. John28215000.0000
3Orato bens35328000.0000
4Ban G50250000.0000
5Alfredo30120000.0000

and tbl_Department:

department_iddepartment_namemax_salary
1Sales50000.00
2HR100000.00
3Production500000.00
4Marketting500000.00

So i have created a model of the Employee in this way:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace MvcApplication1.Models
{
    public class Employee 
    {
        public List<SelectListItem> Department_List { get; set; }
        public List<Employee> Employee_Grid { get; set; }
        public int EmployeeId { get; set; }
        public string EmpName { get; set; }
        public Nullable<int> Age { get; set; }
        public Nullable<decimal> Salary { get; set; }
        public Nullable<int> Department_id { get; set; }
        public string Department { get; set; }
    }
 
}

This is the main view named ‘Index.cshtml’ that contains a DropDownList and Partial View. DropDownList is binding with Department_List that is the collection of the all departments name.

@model MvcApplication1.Models.Employee
@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
<table>
    <tr>
        <td>
            @Html.DropDownList("lstdepartment", Model.Department_List)
        </td>
    </tr>
    <tr>
        <td>
            <div id="EmployeeViewGrid">
               @Html.Partial("EmployeeView",Model.Employee_Grid)
            </div>   
        </td>
    </tr>
</table>
 
<script type="text/javascript">
    $('#lstdepartment').change(function (e) {
        e.preventDefault();
        var url = '@Url.Action("Filter")';
        $.get(url, { department: $(this).val() }, function (result) {
            debugger;
            $('#EmployeeViewGrid').html(result);
        });
    });
</script>

This is the Partial view for the webgrid that will contain the details of the employees:

@model List< MvcApplication1.Models.Employee>
@{
    ViewBag.Title = "EmployeeView";
}
 
<h2>EmployeeView</h2>
<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
    @{
        var grid1 = new WebGrid(source: Model, canPage: true, rowsPerPage: 5, ajaxUpdateContainerId: "gridContent");
 
        @grid1.GetHtml(mode: WebGridPagerModes.All, tableStyle: "webGrid",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            selectedRowStyle: "select",
            rowStyle: "description",
            htmlAttributes: new { id = "positionGrid" },
            fillEmptyRows: false,
 
            columns: grid1.Columns(
 
             grid1.Column("EmployeeId", header: "EmployeeId"),
             grid1.Column("EmpName", header: "EmpName"),
             grid1.Column("Age", header: "Age"),
             grid1.Column("Department", header: "Department"),
             grid1.Column("Salary", header: "Salary")))
    }
</div>

From the above i am using the UrlHelper to hit the url to my controller action ‘Filter‘ as first paramter in $.get method. And second parameter is the selected value of the dropdown. And then on the success callback of the ajax request and i am updating the ‘EmployeeViewGrid‘ div with the results returned by the controller action.(See the controller code below).

Notice that your view have the correct implementation of the jQuery libraries otherwise you will not be able to call ajax methods. So include the bundle of the jQuery libraries. You can also implement the error callback in the $.get method.

Here is the controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
 
namespace MvcApplication1.Controllers
{
    public class EmployeeController : Controller
    {
        private EmployeeDatabaseEntities1 db = new EmployeeDatabaseEntities1();
 
        //
        // GET: /Employee/
 
        public ActionResult Index()
        {
            Employee _model = new Employee();
            //_model.Employee_Grid = db.tbl_Employee.ToList();
            var departmentlist = db.tbl_department.ToList();
 
            _model.Department_List = (from d in departmentlist
                                      select new SelectListItem
                    {
 
                        Value = d.department_id.ToString(),
                        Text = d.department_name
                    }).ToList();
 
            var qq = (from e in db.tbl_Employee
                      join d in db.tbl_department on e.Department_id equals d.department_id
                      select new Employee
                      {
                          Department_id=e.Department_id,
                          EmployeeId=e.EmployeeId,
                          EmpName=e.EmpName,
                          Age=e.Age,
                          Department=d.department_name
                      }).ToList();
            _model.Employee_Grid = qq;
            return View("Index", _model);
        }
 
 
        public ActionResult Filter(string department)
        {
            int? department_id = Convert.ToInt32(department);
       var qq = (from e in db.tbl_Employee
                      join d in db.tbl_department on e.Department_id equals d.department_id
                 where e.Department_id == department_id
                      select new Employee
                      {
                          Department_id = e.Department_id,
                          EmployeeId = e.EmployeeId,
                          EmpName = e.EmpName,
                          Age = e.Age,
                          Department = d.department_name
                      }).ToList();
               return PartialView("EmployeeView",qq);
        }
}
}

Filter records webgrid in mvc4

24 thoughts on “Filtering records in WebGrid using dropdownlist in MVC”

  1. I have tried your method and was able to get a webgrid to both filter and sort. I can sort it and it works. I can filter and it works. BUT if I filter THEN sort, when I click on the heading to sort, it takes me to only my partial view on screen with no css, and no parent view/layout. help?

    1. The value on the ajaxUpdateContainerId needs to be associated with the value on htmlAttributes (which is “positionGrid”).

      What resolved this for me was replacing the following:
      var grid1 = new WebGrid(source: Model, canPage: true, rowsPerPage: 5, ajaxUpdateContainerId: “gridContent”);

      with the following:
      var grid1 = new WebGrid(source: Model, canPage: true, rowsPerPage: 5, ajaxUpdateContainerId: “positionGrid”);

Comments are closed.