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.
- View with Form Post method
- 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:
- public class EmployeeModel
- {
- public int EmployeeId
- {
- get;
- set;
- }
- public string EmpName
- {
- get;
- set;
- }
- public double Salary
- {
- get;
- set;
- }
- public List < EmployeeModel > listEmp
- {
- get;
- set;
- }
-
- public IEnumerable < SelectListItem > EmployeeListItems
- {
- get
- {
- return new SelectList(listEmp, "EmployeeId", "EmpName");
- }
- }
- }
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.
- #region private method to get employee records form database
- private List < EmployeeModel > GetEmployeeDataFromDB()
- {
-
- var listEmp = new List < EmployeeModel > ();
- var emp1 = new EmployeeModel();
- emp1.EmployeeId = 1;
- emp1.EmpName = "Employee1";
- emp1.Salary = 50000;
- var emp2 = new EmployeeModel();
- emp2.EmployeeId = 2;
- emp2.EmpName = "Employee2";
- emp2.Salary = 56000;
- var emp3 = new EmployeeModel();
- emp3.EmployeeId = 3;
- emp3.EmpName = "Employee3";
- emp3.Salary = 60000;
- listEmp.Add(emp1);
- listEmp.Add(emp2);
- listEmp.Add(emp3);
- return listEmp;
- }
- #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.
- public class EmployeeController: Controller
- {
- #region Example with Form Post method
- public ActionResult Employee()
- {
- var employeeModel = new EmployeeModel();
- employeeModel.listEmp = GetEmployeeDataFromDB();
-
- employeeModel.EmployeeId = employeeModel.listEmp.First().EmployeeId;
- employeeModel.EmpName = employeeModel.listEmp.First().EmpName;
- employeeModel.Salary = employeeModel.listEmp.First().Salary;
- return View(employeeModel);
- }
- [HttpPost]
- public ActionResult Employee(EmployeeModel model)
- {
- var employeeModel = new EmployeeModel();
- employeeModel.listEmp = GetEmployeeDataFromDB();
-
-
-
-
- var emp = employeeModel.listEmp.Where(e => e.EmployeeId == model.EmployeeId).FirstOrDefault();
-
- employeeModel.EmployeeId = emp.EmployeeId;
- employeeModel.EmpName = emp.EmpName;
- employeeModel.Salary = emp.Salary;
- return View(employeeModel);
- }
- #endregion
-
- }
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.
- @model MvcApplication1.Models.EmployeeModel
- @{
- ViewBag.Title = "Employee";
- }
-
- <h2>Employee</h2>
- @using (Html.BeginForm("Employee", "Employee", FormMethod.Post, new { id = "demoForm", name = "demoForm" }))
- {
- @Html.DropDownListFor(m => m.EmployeeId, Model.EmployeeListItems, "---Select Employee---", new { Class = "ddlStyle", onchange = "SelectedIndexChanged()" })
-
- <fieldset>
- <legend>EmployeeModel</legend>
- <div class="display-label">
- <strong> @Html.DisplayNameFor(model => model.EmployeeId) </strong>
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.EmployeeId)
- </div>
- <div class="display-label">
- <strong> @Html.DisplayNameFor(model => model.EmpName) </strong>
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.EmpName)
- </div>
- <div class="display-label">
- <strong> @Html.DisplayNameFor(model => model.Salary) </strong>
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.Salary)
- </div>
- </fieldset>
- }
-
- <script type="text/javascript">
- function SelectedIndexChanged() {
-
- document.demoForm.submit();
- }
- </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().
- <script type="text/javascript">
- function SelectedIndexChanged()
- {
-
- document.demoForm.submit();
- }
- </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.
-
-
-
- @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:
- #region Example with Partial View
-
- public ActionResult Index()
- {
- var employeeModel = new EmployeeModel();
- employeeModel.listEmp = GetEmployeeDataFromDB();
-
- employeeModel.EmployeeId = employeeModel.listEmp.First().EmployeeId;
- employeeModel.EmpName = employeeModel.listEmp.First().EmpName;
- employeeModel.Salary = employeeModel.listEmp.First().Salary;
- return View(employeeModel);
- }
-
-
-
-
-
-
- public PartialViewResult GetEmployeeRecord(int EmployeeId)
- {
- var employeeModel = new EmployeeModel();
- employeeModel.listEmp = GetEmployeeDataFromDB();
- var emp = employeeModel.listEmp.Where(e => e.EmployeeId == EmployeeId).FirstOrDefault();
-
- employeeModel.EmployeeId = emp.EmployeeId;
- employeeModel.EmpName = emp.EmpName;
- employeeModel.Salary = emp.Salary;
- return PartialView("_EmpTestPartial", employeeModel);
- }#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.
- @model MvcApplication1.Models.EmployeeModel
-
- <fieldset>
- <legend>EmployeeModel</legend>
- <div class="display-label">
- <strong> @Html.DisplayNameFor(model => model.EmployeeId) </strong>
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.EmployeeId)
- </div>
- <div class="display-label">
- <strong> @Html.DisplayNameFor(model => model.EmpName) </strong>
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.EmpName)
- </div>
- <div class="display-label">
- <strong> @Html.DisplayNameFor(model => model.Salary) </strong>
- </div>
- <div class="display-field">
- @Html.DisplayFor(model => model.Salary)
- </div>
- </fieldset>
This partial view will be used on Index View. So now we will create a View for Index Action().
Index View
- @model MvcApplication1.Models.EmployeeModel
- @
- {
- ViewBag.Title = "Index";
- } < h2 > EmployeeResult < /h2>
- @Html.DropDownListFor(m => m.EmployeeId, Model.EmployeeListItems, "---Select Employee---", new
- {
- Class = "ddlStyle", id = "ddlEmployee"
- }) < div id = "partialDiv" >
- @Html.Partial("_EmpTestPartial") < /div> < script >
- $(document).ready(function()
- {
- $("#ddlEmployee").on("change", function()
- {
- $.ajax(
- {
- url: '/Home/GetEmployeeRecord?EmployeeId=' + $(this).attr("value"),
- type: 'GET',
- data: "",
- contentType: 'application/json; charset=utf-8',
- success: function(data)
- {
- $("#partialDiv").html(data);
- },
- error: function()
- {
- alert("error");
- }
- });
- });
- }); < /script>
In above sample, partial view has been placed in a div partialDiv, see here once again,
- <div id="partialDiv">
- @Html.Partial("_EmpTestPartial")
- </div>
DropdownList Selected Index Change Event
- @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.
- $(document).ready(function()
- {
- $("#ddlEmployee").on("change", function()
- {
- $.ajax(
- {
- url: '/Employee/GetEmployeeRecord?EmployeeId=' + $(this).attr("value"),
- type: 'GET',
- data: "",
- contentType: 'application/json; charset=utf-8',
- success: function(data)
- {
- $("#partialDiv").html(data);
- },
- error: function()
- {
- alert("error");
- }
- });
- });
- }); < /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.
- success: function (data) {
- $("#partialDiv").html(data);
- },
And it's done. Finally, you will get a screen like below:
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.