DropDownList Selected Index Changed Event In MVC

Nowadays, a very common task for any MVC developer is "How to handle Dropdown list Selected Index Changed event in MVC?". This article will show how to handle it in different ways.

  1. View with Form Post method
  2. Partial View with ajax/jQuery GET method

First of all, we will take an example where we need to show Employee data on the page, and one DropDownList for Employee List. And on selection change of DropDownList will show employee records based on selected Employee Id.

So first, we will make a model for Employee.

EmployeeModel:

  1. public class EmployeeModel  
  2. {  
  3.     public int EmployeeId  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string EmpName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public double Salary  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public List < EmployeeModel > listEmp  
  19.         {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         //This property will be used to populate employee dropdownlist  
  24.     public IEnumerable < SelectListItem > EmployeeListItems  
  25.     {  
  26.         get  
  27.         {  
  28.             return new SelectList(listEmp, "EmployeeId""EmpName");  
  29.         }  
  30.     }  
  31. }  
Method to get Employee records

Now, we need to create a method to get data from the database (Here in this article, I am not showing how to get data from the database, just creating data in method only). You can change the functionality of this method to write SQL query or any other way to fetch data from your database server.
  1. #region private method to get employee records form database  
  2. private List < EmployeeModel > GetEmployeeDataFromDB()  
  3. {  
  4.     //Here you can write your query to fetch data from db  
  5.     var listEmp = new List < EmployeeModel > ();  
  6.     var emp1 = new EmployeeModel();  
  7.     emp1.EmployeeId = 1;  
  8.     emp1.EmpName = "Employee1";  
  9.     emp1.Salary = 50000;  
  10.     var emp2 = new EmployeeModel();  
  11.     emp2.EmployeeId = 2;  
  12.     emp2.EmpName = "Employee2";  
  13.     emp2.Salary = 56000;  
  14.     var emp3 = new EmployeeModel();  
  15.     emp3.EmployeeId = 3;  
  16.     emp3.EmpName = "Employee3";  
  17.     emp3.Salary = 60000;  
  18.     listEmp.Add(emp1);  
  19.     listEmp.Add(emp2);  
  20.     listEmp.Add(emp3);  
  21.     return listEmp;  
  22. }  
  23. #endregion  
Controller

Now, we will create an Employee controller that will call above method to get employee records and return it to the corresponding View through Employee model.
  1. public class EmployeeController: Controller  
  2. {  
  3.     #region Example with Form Post method  
  4.     public ActionResult Employee()  
  5.     {  
  6.         var employeeModel = new EmployeeModel();  
  7.         employeeModel.listEmp = GetEmployeeDataFromDB();  
  8.         //Set default employee records  
  9.         employeeModel.EmployeeId = employeeModel.listEmp.First().EmployeeId;  
  10.         employeeModel.EmpName = employeeModel.listEmp.First().EmpName;  
  11.         employeeModel.Salary = employeeModel.listEmp.First().Salary;  
  12.         return View(employeeModel);  
  13.     }  
  14.     [HttpPost]  
  15.     public ActionResult Employee(EmployeeModel model)  
  16.     {  
  17.         var employeeModel = new EmployeeModel();  
  18.         employeeModel.listEmp = GetEmployeeDataFromDB();  
  19.   
  20.         //Filter employeeData based on EmployeeId  
  21.         //This filter part you can do through sql queries also.  
  22.         //Here model.EmployeeId is Dropdownlist selected EmployeeId.  
  23.         var emp = employeeModel.listEmp.Where(e => e.EmployeeId == model.EmployeeId).FirstOrDefault();  
  24.         //Set default emp records  
  25.         employeeModel.EmployeeId = emp.EmployeeId;  
  26.         employeeModel.EmpName = emp.EmpName;  
  27.         employeeModel.Salary = emp.Salary;  
  28.         return View(employeeModel);  
  29.     }  
  30.     #endregion  
  31.       
  32. }  
In the above sample, first Action Employee() is to load all Employee List in the dropdown list and one default employee record.

As dropdown list selection will be changed, Form Post method will be called and that is second Action Employee() mentioned in above sample.

We will see later how dropdown list selected index changed call Post Action.

View

1. View with Form Post method

In this section, we will see how View works with Form Post method.

We need one view to Employee Records.

  1. @model MvcApplication1.Models.EmployeeModel  
  2. @{  
  3.     ViewBag.Title = "Employee";  
  4. }  
  5.   
  6. <h2>Employee</h2>  
  7.     @using (Html.BeginForm("Employee""Employee", FormMethod.Post, new { id = "demoForm", name = "demoForm" }))  
  8.     {  
  9.         @Html.DropDownListFor(m => m.EmployeeId, Model.EmployeeListItems, "---Select Employee---"new { Class = "ddlStyle", onchange = "SelectedIndexChanged()" })  
  10.   
  11.     <fieldset>  
  12.         <legend>EmployeeModel</legend>  
  13.         <div class="display-label">  
  14.             <strong> @Html.DisplayNameFor(model => model.EmployeeId) </strong>  
  15.         </div>  
  16.         <div class="display-field">  
  17.             @Html.DisplayFor(model => model.EmployeeId)  
  18.         </div>  
  19.         <div class="display-label">  
  20.             <strong> @Html.DisplayNameFor(model => model.EmpName) </strong>  
  21.         </div>  
  22.         <div class="display-field">  
  23.             @Html.DisplayFor(model => model.EmpName)  
  24.         </div>  
  25.         <div class="display-label">  
  26.             <strong> @Html.DisplayNameFor(model => model.Salary) </strong>  
  27.         </div>  
  28.         <div class="display-field">  
  29.             @Html.DisplayFor(model => model.Salary)  
  30.         </div>  
  31.     </fieldset>  
  32. }  
  33.   
  34. <script type="text/javascript">  
  35.     function SelectedIndexChanged() {  
  36.         //Form post  
  37.         document.demoForm.submit();  
  38.     }  
  39. </script>  

DropDownList Selected Index Changed Event: In above View sample, the dropdown list has an on change event and that will hit JavaScript method SelectedIndexChanged().

  1. <script type="text/javascript">  
  2.     function SelectedIndexChanged()  
  3.     {  
  4.         //Form post  
  5.         document.demoForm.submit();  
  6.     }  
  7. </script>  
document.demoForm.submit() method will post this form (demoForm is the name of current form), and that will hit Post type Action Employee (Employee model) in the controller.

How Selected Employee Id will be passed to controller action

If you have noticed we have mentioned Model.EmployeeId as an expression.

  1. // An expression that identifies the object that contains the properties to  
  2.   
  3. // display.  
  4. @Html.DropDownListFor(m => m.EmployeeId, Model.EmployeeListItems............  
So in Post action, passed model will have selected Employee Id as model.EmployeeId.

Post action Employee(Employee model)

This action will fetch employee records through a private method GetEmployeeDataFromDB() in above controller sample.

It will filter data based on Model.EmployeeId and return filtered model again to view.

2. Partial View with ajax/jQuery GET method

This section will describe how we can use Partial View to load Employee Records based on Selected Employee Id in dropdown list.

For this now we will have two separate Actions so it will not be confused with the above sample.

Actions that will support Partial View:
  1. #region Example with Partial View  
  2. // GET: /Employee/  
  3. public ActionResult Index()  
  4. {  
  5.     var employeeModel = new EmployeeModel();  
  6.     employeeModel.listEmp = GetEmployeeDataFromDB();  
  7.     //Set default emp records  
  8.     employeeModel.EmployeeId = employeeModel.listEmp.First().EmployeeId;  
  9.     employeeModel.EmpName = employeeModel.listEmp.First().EmpName;  
  10.     employeeModel.Salary = employeeModel.listEmp.First().Salary;  
  11.     return View(employeeModel);  
  12. }  
  13.   
  14. /// <summary>  
  15. /// This method will return PartialView with Employee Model  
  16. /// </summary>  
  17. /// <param name="EmployeeId"></param>  
  18. /// <returns></returns>  
  19. public PartialViewResult GetEmployeeRecord(int EmployeeId)  
  20. {  
  21.     var employeeModel = new EmployeeModel();  
  22.     employeeModel.listEmp = GetEmployeeDataFromDB();  
  23.     var emp = employeeModel.listEmp.Where(e => e.EmployeeId == EmployeeId).FirstOrDefault();  
  24.     //Set default emp records  
  25.     employeeModel.EmployeeId = emp.EmployeeId;  
  26.     employeeModel.EmpName = emp.EmpName;  
  27.     employeeModel.Salary = emp.Salary;  
  28.     return PartialView("_EmpTestPartial", employeeModel);  
  29. }#endregion  
In the above sample, First Action Index() is to load default Employee Records and Employee List for DropDownList.
And second Action GetEmployeeRecord (int EmployeeId) is to return a partial view "_EmpTestPartial" with filtered employee records based on passed EmployeeId parameter.

Partial View

Create a partial view to show Employee Records.
  1. @model MvcApplication1.Models.EmployeeModel  
  2.   
  3. <fieldset>  
  4.     <legend>EmployeeModel</legend>  
  5.     <div class="display-label">  
  6.         <strong> @Html.DisplayNameFor(model => model.EmployeeId) </strong>  
  7.     </div>  
  8.     <div class="display-field">  
  9. @Html.DisplayFor(model => model.EmployeeId)  
  10. </div>  
  11.     <div class="display-label">  
  12.         <strong> @Html.DisplayNameFor(model => model.EmpName) </strong>  
  13.     </div>  
  14.     <div class="display-field">  
  15. @Html.DisplayFor(model => model.EmpName)  
  16. </div>  
  17.     <div class="display-label">  
  18.         <strong> @Html.DisplayNameFor(model => model.Salary) </strong>  
  19.     </div>  
  20.     <div class="display-field">  
  21. @Html.DisplayFor(model => model.Salary)  
  22. </div>  
  23. </fieldset>  
This partial view will be used on Index View. So now we will create a View for Index Action().

Index View
  1. @model MvcApplication1.Models.EmployeeModel  
  2. @  
  3. {  
  4.     ViewBag.Title = "Index";  
  5. } < h2 > EmployeeResult < /h2>  
  6. @Html.DropDownListFor(m => m.EmployeeId, Model.EmployeeListItems, "---Select Employee---"new  
  7.     {  
  8.         Class = "ddlStyle", id = "ddlEmployee"  
  9.     }) < div id = "partialDiv" >  
  10.     @Html.Partial("_EmpTestPartial") < /div> < script >  
  11.     $(document).ready(function()  
  12.     {  
  13.         $("#ddlEmployee").on("change", function()  
  14.         {  
  15.             $.ajax(  
  16.             {  
  17.                 url: '/Home/GetEmployeeRecord?EmployeeId=' + $(this).attr("value"),  
  18.                 type: 'GET',  
  19.                 data: "",  
  20.                 contentType: 'application/json; charset=utf-8',  
  21.                 success: function(data)  
  22.                 {  
  23.                     $("#partialDiv").html(data);  
  24.                 },  
  25.                 error: function()  
  26.                 {  
  27.                     alert("error");  
  28.                 }  
  29.             });  
  30.         });  
  31.     }); < /script>  
In above sample, partial view has been placed in a div partialDiv, see here once again,
  1. <div id="partialDiv">  
  2.    @Html.Partial("_EmpTestPartial")  
  3. </div>  
DropdownList Selected Index Change Event
  1. @Html.DropDownListFor(m => m.EmployeeId, Model.EmployeeListItems, "---Select Employee---"new { Class = "ddlStyle", id = "ddlEmployee" })  
If you see in above dropdownlist control, we do not have any JavaScript method called on OnChange event.

jQuery event for DropDownList Selected Index Changed event

DropDownList control has ID ddlEmployee and onchange method for this control is mentioned in jQuery document.ready() function.
  1. $(document).ready(function()  
  2. {  
  3.     $("#ddlEmployee").on("change", function()  
  4.     {  
  5.         $.ajax(  
  6.         {  
  7.             url: '/Employee/GetEmployeeRecord?EmployeeId=' + $(this).attr("value"),  
  8.             type: 'GET',  
  9.             data: "",  
  10.             contentType: 'application/json; charset=utf-8',  
  11.             success: function(data)  
  12.             {  
  13.                 $("#partialDiv").html(data);  
  14.             },  
  15.             error: function()  
  16.             {  
  17.                 alert("error");  
  18.             }  
  19.         });  
  20.     });  
  21. }); < /script>  
AJAX GET method

$.ajax({.....}) is a method to call a given Url without loading full page that's why we should use Partial View to refresh data on a page.

Selected EmployeeId in DropdownList is passed in GetEmployeeRecord() action through Querystring.

url: '/Home/GetEmployeeRecord?EmployeeId=' + $(this).attr("value")

How returned Partial View will be loaded on View

In Ajax GET method, we have written success method. If called Action GetEmployeeRecord(int EmployeeId) will return Partial View successfully so returned partial view will be placed in div "partialDiv", as below it shown.
  1. success: function (data) {  
  2.    $("#partialDiv").html(data);  
  3. },  
And it's done. Finally, you will get a screen like below:

result

I hope this article will help to developers who are/will be looking for DropdownList selected index changed event in MVC.

I have attached source code also. You can download full code as explained above in this blog.