Creating a Cascading Dropdown List in MVC 4

For this I will create a new MVC 4 application.

Open Visual Studio 2012 then select "File" -> "New" -> "Project..."



Now add a new ADO.NET Entity data model.



Enter your SQL Server credentials here.







Now add a new Controller.



Now do the following code here in Employee Controller:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using CascadingDropDownInMVC4.Models;  
  7. namespace CascadingDropDownInMVC4.Controllers  
  8. {  
  9.     public class EmployeeController : Controller  
  10.     {  
  11.         public ActionResult Index()  
  12.         {  
  13.             EmployeeManagementEntities db = new EmployeeManagementEntities();  
  14.             ViewBag.Country = new SelectList(db.Country, "CountryID""CountryName");  
  15.             return View();  
  16.         }  
  17.   
  18.         // Json Call to get state  
  19.         public JsonResult GetStates(string id)  
  20.         {  
  21.             List<SelectListItem> states = new List<SelectListItem>();  
  22.             var stateList = this.Getstate(Convert.ToInt32(id));  
  23.             var stateData = stateList.Select(m => new SelectListItem()  
  24.             {  
  25.                 Text = m.StateName,  
  26.                 Value = m.StateID.ToString(),  
  27.             });  
  28.             return Json(stateData, JsonRequestBehavior.AllowGet);  
  29.         }  
  30.   
  31.         // Get State from DB by country ID  
  32.         public IList<State> Getstate(int CountryId)  
  33.         {  
  34.             EmployeeManagementEntities db = new EmployeeManagementEntities();  
  35.   
  36.             return db.State.Where(m => m.CountryID == CountryId).ToList();  
  37.         }  
  38.         [HttpPost]  
  39.         public ActionResult Index(FormCollection formdata)  
  40.         {  
  41.             // Get Employee informaiton to insert into Data Base  
  42.             return RedirectToAction("Index""Home");  
  43.         }  
  44.     }  
  45. }  
Now add a View index.cshtml as in the following:
  1. @model CascadingDropDownInMVC4.Models.EmployeeData  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8.   
  9. @using (Html.BeginForm())  
  10. {  
  11.     @Html.ValidationSummary(true)  
  12.   
  13.     <fieldset>  
  14.         <legend>EmployeeData</legend>  
  15.   
  16.         <div class="editor-label">  
  17.             @Html.LabelFor(model => model.Name)  
  18.         </div>  
  19.         <div class="editor-field">  
  20.             @Html.EditorFor(model => model.Name)  
  21.             @Html.ValidationMessageFor(model => model.Name)  
  22.         </div>  
  23.   
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(model => model.Email)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.EditorFor(model => model.Email)  
  29.             @Html.ValidationMessageFor(model => model.Email)  
  30.         </div>  
  31.   
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(model => model.Designation)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.             @Html.EditorFor(model => model.Designation)  
  37.             @Html.ValidationMessageFor(model => model.Designation)  
  38.         </div>  
  39.         <div class="editor-label">  
  40.             @Html.Label("Country")<br />  
  41.         </div>  
  42.            
  43.         <div>  
  44.             @Html.DropDownList("Country", ViewBag.Country as SelectList, "-- Please Select a Country  --"new { style="width:250px"})  
  45.   
  46.         </div>  
  47.         <div class="editor-label"><br />  
  48.             @Html.Label("State")<br />  
  49.         </div>  
  50.         <div>  
  51.             @Html.DropDownList("State"new SelectList(string.Empty, "Value""Text"), "-- Please select a State --"new { style = "width:250px", @class = "dropdown1" })  
  52.         </div>  
  53.         <p>  
  54.             <input type="submit" value="Create" />  
  55.         </p>  
  56.     </fieldset>  
  57. }  
  58.   
  59. <script src="~/Scripts/jquery-1.7.1.js"></script>  
  60. <script src="~/Scripts/jquery-1.7.1.min.js"></script>  
  61.   
  62. <script type="text/javascript">  
  63.     $(document).ready(function () {  
  64.         //Country Dropdown Selectedchange event  
  65.         $("#Country").change(function () {  
  66.             $("#State").empty();  
  67.             $.ajax({  
  68.                 type: 'POST',  
  69.                 url: '@Url.Action("GetStates")'// Calling json method  
  70.                 dataType: 'json',  
  71.                 data: { id: $("#Country").val() },  
  72.                 // Get Selected Country ID.  
  73.                 success: function (states) {  
  74.                     $.each(states, function (i, state) {  
  75.                         $("#State").append('<option value="' + state.Value + '">' +  
  76.                              state.Text + '</option>');  
  77.                     });  
  78.                 },  
  79.                 error: function (ex) {  
  80.                     alert('Failed to retrieve states.' + ex);  
  81.                 }  
  82.             });  
  83.             return false;  
  84.         })  
  85.     });  
  86. </script>  
Now run the application as in the following:

Now select a country as in the following:





Now I have 2 tables for Country & State.



The following is the data in my Country table:

The following is the data in my State table:


Similar Articles