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‘:

EmployeeId Empname Age Department_id Salary
1 David 30 1 25000.0000
2 A. John 28 2 15000.0000
3 Orato bens 35 3 28000.0000
4 Ban G 50 2 50000.0000
5 Alfredo 30 1 20000.0000

and tbl_Department:

department_id department_name max_salary
1 Sales 50000.00
2 HR 100000.00
3 Production 500000.00
4 Marketting 500000.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