Creating Simple Cascading DropDownList In MVC 4 Using Razor

This article shows how to create a Cascading Dropdownlist.

Use JSON with razor syntax.

CascadingDropDown enables a common scenario in which the contents of one list depends on the selection of another list and does so without having to embed the entire data set in the page or transfer it to the client at all.

The main purpose is to reduce Postbacks.

Let's start.

Srep 1: Create a project then select Web from above Menu in left

Step 2: Select ASP.NET MVC 4 Web Application.

MVC 4 Web Application

Internet Application

And name it Cascadingdropdownlist.

Step 3: After creating the application we will add a Controller to the page.

For adding the Controller right-click on the Controller Folder and select Add inside add Select Controller.

Adding Controller

Controller

And I am naming the Contoller CustomerFeedbackController.cs.

Step 4: After adding the Controller to the application I am now just adding a new action result and naming it LoadCountries.

  1. public ActionResult LoadCountries()  
  2. {  
  3.      List<SelectListItem> li = new List<SelectListItem>();  
  4.      li.Add(new SelectListItem { Text = "Select", Value = "0" });  
  5.      li.Add(new SelectListItem { Text = "India", Value = "1" });  
  6.      li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });  
  7.      li.Add(new SelectListItem { Text = "China", Value = "3" });  
  8.      li.Add(new SelectListItem { Text = "Austrila", Value = "4" });  
  9.      li.Add(new SelectListItem { Text = "USA", Value = "5" });  
  10.      li.Add(new SelectListItem { Text = "UK", Value = "6" });  
  11.      ViewData["country"] = li;  
  12.      return View();  
  13. }  

In this I created a Generic List and in the list I am adding an item to it.

After adding it I am storing it in ViewData for passing to the view.

Step 5: For adding the View to LoadCountries rigtht-click on the loadCountries and select Add View.

Add View

Add a click on the Add Button. Add Razor Syntax to the Begin Form.

  1. @using (Html.BeginForm())  
  2. {  
  3. }  
Step 6: Add a Dropdown list with Name of Countries and Binding ViewData to the Dropdownlist. 

  1. @using (Html.BeginForm())  
  2. {  
  3.     @Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>)  
  4. }  

Now just run the application and check how it is output.

just run application

The preceding was a simple example of how to bind a list to a Dropdownlist in MVC.

Now we will be doing a Cascading Dropdown Demo. For that we would be writing a JSON script and JSON method.

And add two DropDownLists with an empty Datasource.

Step 7:

  1. State DropDownList
    1. @Html.DropDownList("State"new SelectList(string.Empty, "Value""Text"), "Please select a State"new { style = "width:250px", @class = "dropdown1" })   
  2. City DropDownList
    1. @Html.DropDownList("city"new SelectList(string.Empty, "Value""Text"), "Please select a city"new { style = "width:250px", @class = "dropdown1" })  

Now we have added two DropDownLists.

Here is a Snapshot of the View:

Snapshot of View

Step 8: Further we will be adding a method for the JSON and a script for JSON for the States.

Just below I have added the method for JSON.

And also you will see the method for JSON is taking an input parameter, id (this is the id of the Country Dropdownlist that I created).

The Script for JSON will be called when the Country Dropdownlist is selected.

  1. public JsonResult GetStates(string id)  
  2. {  
  3.     List<SelectListItem> states = new List<SelectListItem>();  
  4.     switch (id)  
  5.     {  
  6.         case "1":  
  7.              states.Add(new SelectListItem { Text = "Select", Value = "0" });  
  8.              states.Add(new SelectListItem { Text = "ANDAMAN & NIKOBAR ISLANDS", Value = "1" });  
  9.              states.Add(new SelectListItem { Text = "ANDHRA PRADESH", Value = "2" });  
  10.              states.Add(new SelectListItem { Text = "ARUNACHAL PRADESH", Value = "3" });  
  11.              states.Add(new SelectListItem { Text = "ASSAM", Value = "4" });  
  12.              states.Add(new SelectListItem { Text = "BIHAR", Value = "5" });  
  13.              states.Add(new SelectListItem { Text = "CHANDIGARH", Value = "6" });  
  14.              states.Add(new SelectListItem { Text = "CHHATTISGARH", Value = "7" });  
  15.              states.Add(new SelectListItem { Text = "DADRA & NAGAR HAVELI", Value = "8" });  
  16.              states.Add(new SelectListItem { Text = "DAMAN & DIU", Value = "9" });  
  17.              states.Add(new SelectListItem { Text = "GOA", Value = "10" });  
  18.              states.Add(new SelectListItem { Text = "GUJARAT", Value = "11" });  
  19.              states.Add(new SelectListItem { Text = "HARYANA", Value = "12" });  
  20.              states.Add(new SelectListItem { Text = "HIMACHAL PRADESH", Value = "13" });  
  21.              states.Add(new SelectListItem { Text = "JAMMU & KASHMIR", Value = "14" });  
  22.               states.Add(new SelectListItem { Text = "JHARKHAND", Value = "15" });  
  23.               states.Add(new SelectListItem { Text = "KARNATAKA", Value = "16" });  
  24.               states.Add(new SelectListItem { Text = "KERALA", Value = "17" });  
  25.               states.Add(new SelectListItem { Text = "LAKSHADWEEP", Value = "18" });  
  26.               states.Add(new SelectListItem { Text = "MADHYA PRADESH", Value = "19" });  
  27.               states.Add(new SelectListItem { Text = "MAHARASHTRA", Value = "20" });  
  28.               states.Add(new SelectListItem { Text = "MANIPUR", Value = "21" });  
  29.               states.Add(new SelectListItem { Text = "MEGHALAYA", Value = "22" });  
  30.               states.Add(new SelectListItem { Text = "MIZORAM", Value = "23" });  
  31.               states.Add(new SelectListItem { Text = "NAGALAND", Value = "24" });  
  32.               states.Add(new SelectListItem { Text = "NCT OF DELHI", Value = "25" });  
  33.               states.Add(new SelectListItem { Text = "ORISSA", Value = "26" });  
  34.               states.Add(new SelectListItem { Text = "PUDUCHERRY", Value = "27" });  
  35.                states.Add(new SelectListItem { Text = "PUNJAB", Value = "28" });  
  36.                states.Add(new SelectListItem { Text = "RAJASTHAN", Value = "29" });  
  37.                states.Add(new SelectListItem { Text = "SIKKIM", Value = "30" });  
  38.                states.Add(new SelectListItem { Text = "TAMIL NADU", Value = "31" });  
  39.                states.Add(new SelectListItem { Text = "TRIPURA", Value = "32" });  
  40.                states.Add(new SelectListItem { Text = "UTTAR PRADESH", Value = "33" });  
  41.                states.Add(new SelectListItem { Text = "UTTARAKHAND", Value = "34" });  
  42.                states.Add(new SelectListItem { Text = "WEST BENGAL", Value = "35" });  
  43.             break;  
  44.                case "UK":  
  45.            break;  
  46.             case "India":  
  47.           break;  
  48.     }  
  49.     return Json(new SelectList(states, "Value""Text"));  
  50. }  

Step 9: After creating the method for JSON I just wrote a script for JSON.

  1. <script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>  
  2. <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>  
  3. <script type="text/javascript">  
  4.     $(document).ready(function () {  
  5.         //Dropdownlist Selectedchange event  
  6.         $("#Country").change(function () {  
  7.             $("#State").empty();  
  8.             $.ajax({  
  9.                 type: 'POST',  
  10.                 url: '@Url.Action("GetStates")'// we are calling json method  
  11.    
  12.                 dataType: 'json',  
  13.    
  14.                 data: { id: $("#Country").val() },   
  15.                // here we are get value of selected country and passing same value  
  16.                   as inputto json method GetStates.  
  17.    
  18.                 success: function (states) {  
  19.                     // states contains the JSON formatted list  
  20.                     // of states passed from the controller  
  21.    
  22.                     $.each(states, function (i, state) {  
  23.                     $("#State").append('<option value="' + state.Value + '">' +    
  24.                          state.Text + '</option>');                                                                                                  
  25.                     // here we are adding option for States  
  26.    
  27.                     });  
  28.                 },  
  29.                 error: function (ex) {  
  30.                     alert('Failed to retrieve states.' + ex);  
  31.                 }  
  32.             });  
  33.             return false;  
  34.         })  
  35.     });  
  36. </script>  

Step 10:

We have just now bound States from Country. We will now bind city from States.

In the same manner I created a method for JSON for binding the City.

  1. public JsonResult GetCity(string id)  
  2. {  
  3.     List<SelectListItem> City = new List<SelectListItem>();  
  4.     switch (id)  
  5.     {  
  6.         case "20":  
  7.             City.Add(new SelectListItem { Text = "Select", Value = "0" });  
  8.             City.Add(new SelectListItem { Text = "MUMBAI", Value = "1" });  
  9.             City.Add(new SelectListItem { Text = "PUNE", Value = "2" });  
  10.             City.Add(new SelectListItem { Text = "KOLHAPUR", Value = "3" });  
  11.             City.Add(new SelectListItem { Text = "RATNAGIRI", Value = "4" });  
  12.             City.Add(new SelectListItem { Text = "NAGPUR", Value = "5" });  
  13.             City.Add(new SelectListItem { Text = "JALGAON", Value = "6" });  
  14.             break;  
  15.     }  
  16.    
  17.     return Json(new SelectList(City, "Value""Text"));  
  18. }  

Step 11:  And also wrote a script for JSON that wil be active when you select States.

  1. <script type="text/javascript">  
  2.     $(document).ready(function () {  
  3.         //Dropdownlist Selectedchange event  
  4.         $("#State").change(function () {  
  5.             $("#city").empty();  
  6.             $.ajax({  
  7.                 type: 'POST',  
  8.                 url: '@Url.Action("GetCity")',  
  9.                 dataType: 'json',  
  10.                 data: { id: $("#State").val() },  
  11.                 success: function (citys) {  
  12.                     // states contains the JSON formatted list  
  13.                     // of states passed from the controller  
  14.                     $.each(citys, function (i, city) {  
  15.                         $("#city").append('<option value="'  
  16. + city.Value + '">'  
  17. + city.Text + '</option>');  
  18.                     });  
  19.                 },  
  20.                 error: function (ex) {  
  21.                     alert('Failed to retrieve states.' + ex);  
  22.                 }  
  23.             });  
  24.             return false;  
  25.         })  
  26.     });  
  27. </script>   

Final step

Countries Dropdown snapshot.

Dropdown

States Dropdown snapshot.

States Dropdown

City Dropdown snapshot.

City Dropdown

And fetching data a post here is a snapshot.

Featching Data


Similar Articles