Cascading DropDownList in ASP.Net MVC

In this article I explain how to make a cascading DropDownList in ASP.Net MVC.

In a Web Form, a DropDownList is common and time to time we need to provide the functionality of cascading between dropdownlists. Today in this article we will learn how to populate a dropdownlist and cascade between those dropdownlists.

How to populate a Dropdownlist in ASP.Net MVC

In this article we have a School database with the following 2 tables.

  1. StateMaster
  2. DistrictMaster

Cascading Drop 1

Step 1

Open Visual Studio then select File >> New >> Project then select ASP.Net MVC 4 Web Application.

Step 2

Select Internet Application then click OK.

Cascading 2

Cascading 3

Step 3

Select the Model folder then create a new Model class.

StudentModel.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MvcDemoApplication.Models  
  8. {  
  9.     public class StudentModel  
  10.     {  
  11.         public IList<SelectListItem> StateNames { get; set; }  
  12.         public IList<SelectListItem> DistrictNames { get; set; }  
  13.     }  
  14. }  

Step 4

Create a .edmx file and connect with the database.

Step 5

Create a new Controller. In this article I create DropDownListController.cs.

DropDownListController.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcDemoApplication.Models;  
  7.   
  8. namespace MvcDemoApplication.Controllers  
  9. {  
  10.     public class DropDownListController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /DropDownList/  
  14.         SchoolEntities schoolEntity = new SchoolEntities();  
  15.         public ActionResult Index()  
  16.         {  
  17.             List<SelectListItem> stateNames = new List<SelectListItem>();  
  18.             StudentModel stuModel=new StudentModel();  
  19.               
  20.             List<StateMaster> states = schoolEntity.StateMasters.ToList();  
  21.             states.ForEach(x =>  
  22.                 {  
  23.           stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
  24.                 });  
  25.             stuModel.StateNames = stateNames;  
  26.             return View(stuModel);  
  27.         }  
  28.           }  
  29. }  
Index.cshtml
  1. @model MvcDemoApplication.Models.StudentModel  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.   
  6. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  7.   
  8. <h2>Cascading Dropdownlist</h2>  
  9. <table>  
  10.     <tr>  
  11.         <td>  
  12.             <label>State</label>  
  13.         </td>  
  14.         <td>  
  15. @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--"new { @id="ddlState"});  
  16.         </td>  
  17.     </tr>  
  18. </table>  
Understand the Code

In Studentmodel we have the following 2 properties:

 

    1. public IList<SelectListItem> StateNames { get; set; }  
    1. public IList<SelectListItem> DistrictNames { get; set; }  
Here we are using the SelectListItem class, this class has the following 3 properties:
  1. Selected: This is a bool type to show in a dropdown (as selected) true or false by default.

  2. Text: This is a string type, for the dropdown text.

  3. Value: This is string type for the value of the dropdown
If you notice in the dropdownlist, we also need the same properties. For this reason we are using SelectListItem in a Ilist.

DropdownlistController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcDemoApplication.Models;  
  7.   
  8. namespace MvcDemoApplication.Controllers  
  9. {  
  10.     public class DropDownListController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /DropDownList/  
  14.         SchoolEntities schoolEntity = new SchoolEntities();  
  15.         public ActionResult Index()  
  16.         {  
  17.             List<SelectListItem> stateNames = new List<SelectListItem>();  
  18.             StudentModel stuModel=new StudentModel();  
  19.               
  20.             List<StateMaster> states = schoolEntity.StateMasters.ToList();  
  21.             states.ForEach(x =>  
  22.                 {  
  23.                     stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
  24.                 });  
  25.             stuModel.StateNames = stateNames;  
  26.             return View(stuModel);  
  27.         }  
  28.     }  
  29. }  
In the preceding code we create the SchoolEntities object, in this object all the related tables exist.
  1. SchoolEntities schoolEntity = new SchoolEntities();  
  2.   
  3. List<StateMaster> states = schoolEntity.StateMasters.ToList();  
In the preceding line of code, all the related data of the StateMasters tables comes into the StateMaster list object.
  1. states.ForEach(x =>  
  2. {  
  3.    stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
  4. });  
Now it is time to add entity data into the Text and value properties, the all collection will be stored into the stateNames object.

Index.cshtml
  1. @model MvcDemoApplication.Models.StudentModel  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.   
  6. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  7.   
  8. <h2>Cascading Dropdownlist</h2>  
  9. <table>  
  10.     <tr>  
  11.         <td>  
  12.             <label>State</label>  
  13.         </td>  
  14.         <td>  
  15.   @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--"new { @id="ddlState"});  
  16.         </td>  
  17.     </tr>  
  18. </table>  
The preceding code shows the model data in View. Now to understand how it works.
  1. @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--"new { @id="ddlState"});  
Look at the preceding code, we used here, @Html helper classes for creating a DropDownList. In the DropDownListFor helper class we used 4 parameters.
  1. x=>x.StateNames: For getting the values of the collection from the entity.

  2. Model.StateNames: Collections of states.

  3. “—Select--”: Default value, when the dropdown list will be populated.

  4. new {@id=”ddlState”}: In this part we can define an id, class and name for the control.
How to do cascading between two dropdownlists.

DropdownlistController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcDemoApplication.Models;  
  7.   
  8. namespace MvcDemoApplication.Controllers  
  9. {  
  10.     public class DropDownListController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /DropDownList/  
  14.         SchoolEntities1 schoolEntity = new SchoolEntities1();  
  15.         public ActionResult Index()  
  16.         {  
  17.             List<SelectListItem> stateNames = new List<SelectListItem>();  
  18.             StudentModel stuModel=new StudentModel();  
  19.               
  20.             List<StateMaster> states = schoolEntity.StateMasters.ToList();  
  21.             states.ForEach(x =>  
  22.                 {  
  23. stateNames.Add(new SelectListItem { Text = x.StateName , Value = x.StateId.ToString() });  
  24.                 });  
  25.             stuModel.StateNames = stateNames;  
  26.             return View(stuModel);  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         public ActionResult GetDistrict(string stateId)  
  31.         {  
  32.             int statId;  
  33.             List<SelectListItem> districtNames = new List<SelectListItem>();  
  34.             if (!string.IsNullOrEmpty(stateId))  
  35.             {  
  36.                 statId = Convert.ToInt32(stateId);  
  37. List<DistrictMaster> districts = schoolEntity.DistrictMasters.Where(x => x.StateId == statId).ToList();  
  38.                 districts.ForEach(x =>  
  39.                 {  
  40. districtNames.Add(new SelectListItem { Text = x.DistrictName, Value = x.DistrictId.ToString() });  
  41.                 });  
  42.             }  
  43.             return Json(districtNames, JsonRequestBehavior.AllowGet);  
  44.         }  
  45.   
  46.     }  
  47. }  
Index.cshtml
  1. @model MvcDemoApplication.Models.StudentModel  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.   
  6. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  7.   
  8. <h2>Cascading Dropdownlist</h2>  
  9. <table>  
  10.     <tr>  
  11.         <td>  
  12.             <label>State</label>  
  13.         </td>  
  14.         <td>  
  15. @Html.DropDownListFor(x => x.StateNames, Model.StateNames, "--Select--"new { @id="ddlState"});  
  16.         </td>  
  17.     </tr>  
  18.     <tr>  
  19.         <td>  
  20.             <label>District</label>  
  21.         </td>  
  22.         <td id="District">  
  23. @Html.DropDownListFor(x => x.DistrictNames, new List<SelectListItem>(), "--Select--"new { @id="ddlDistrict"});  
  24.         </td>  
  25.     </tr>  
  26. </table>  
  27.   
  28. <script type="text/javascript">  
  29.     $(document).ready(function () {  
  30.         $('#ddlState').change(function () {  
  31.             $.ajax({  
  32.                 type: "post",  
  33.                 url: "/DropDownList/GetDistrict",  
  34.                 data: { stateId: $('#ddlState').val() },  
  35.                 datatype: "json",  
  36.                 traditional: true,  
  37.                 success: function (data) {  
  38.                     var district = "<select id='ddlDistrict'>";  
  39.                     district = district + '<option value="">--Select--</option>';  
  40.                     for (var i = 0; i < data.length; i++)  
  41.                     {  
  42.                         district = district + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';  
  43.                     }  
  44.                     district = district + '</select>';  
  45.                     $('#District').html(district);  
  46.                 }  
  47.             });  
  48.         });  
  49.     });  
  50. </script>  
That's it. Press F5 and run your code. For any query please send your comments here.

Cascading 4

Cascading 5