Creating Cascading DropDownList In MVC Using Entity Framework And ADO.NET

Here, I am going to explain cascading drop down list in MVC, using two approaches.
  1. Using ADO.NET
  2. Using Entity framework.
First, I will explain, how to create cascading drop down list in MVC, using ADO.NET. Here, I have the database design as follows:

       

As shown, I have three tables in my database.
  1. First table is tbl_Country(slNo is Primary Key).
  2. Second table is tbl_state(slNo is Primary Key, country code is the secondary key with slNo from tbl_country).
  3. Third table is tbl_city(slNo is the primary key, statecode is the secondary key with slno from tbl_state).
Now, I will write the code for my connection string in Web.Config to set the connection with the database.
  1. <connectionStrings>  
  2.    <add name="Connect" connectionString="Data Source=DEBENDRA;Initial Catalog=CodeX;User ID=sa;Password=123"/>  
  3.  </connectionStrings>  
Now, I will add a class as "DAL.cs" and write the following code to read the connection string and select the data from the different tables.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Data.SqlClient;    
  6. using System.Data;    
  7. using System.Configuration;    
  8. using System.Collections;    
  9. using System.Web.Mvc;    
  10.     
  11. namespace MVC2    
  12. {    
  13.     public  class DAL    
  14.     {    
  15.         DataSet ds;    
  16.         SqlDataAdapter da;    
  17.     
  18.        public static SqlConnection connect()    
  19.         {    
  20.            //Reading the connection string from web.config    
  21.             string Name = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;    
  22.            //Passing the string in sqlconnection.    
  23.             SqlConnection con = new SqlConnection(Name);    
  24.            //Check wheather the connection is close or not if open close it else open it    
  25.            if(con.State==ConnectionState.Open)    
  26.            {    
  27.                con.Close();    
  28.     
  29.            }    
  30.            else    
  31.            {    
  32.              
  33.                con.Open();    
  34.            }    
  35.            return con;    
  36.     
  37.         }    
  38.         //Creating a method which accept any type of query from controller to execute and give result.    
  39.         //result kept in datatable and send back to the controller.    
  40.        public  DataTable MyMethod( string Query)    
  41.        {    
  42.           ds= new DataSet();    
  43.           DataTable dt = new DataTable();    
  44.           da = new SqlDataAdapter(Query, DAL.connect());    
  45.     
  46.           da.Fill(dt);    
  47.            List<SelectListItem> list = new List<SelectListItem>();    
  48.            return dt;    
  49.           
  50.        }    
  51.     
  52.     }    
  53. }    
HOME controller is there to take the data from DAL.Class.
  1. public class HomeController : Controller  
  2.    {  
  3.        DAL objdal = new DAL();  
  4.         
  5.         
  6.   
  7.        public ActionResult Index()  
  8.        {  
  9.            string countrystring = "select * from tbl_Country";  
  10.            DataSet ds = new DataSet();  
  11.            List<string> li = new List<string>();  
  12.           DataTable dt=new DataTable();  
  13.            dt= objdal.MyMethod(countrystring);  
  14.            List<SelectListItem> list = new List<SelectListItem>();  
  15.           foreach (DataRow row in dt.Rows)  
  16.           {  
  17.                
  18.                   list.Add(new SelectListItem { Text =Convert.ToString(row.ItemArray[1]),Value=Convert.ToString(row.ItemArray[0])});  
  19.            
  20.           }  
  21.   
  22.   
  23.   
  24.           ViewBag.country = list;  
  25.   
  26.   
  27.            return View();  
  28.        }  
Now, right click and generate a view for the index.

 Add a drop down list in it.
  1. <div style=" background-color:blanchedalmond; border-color:black; border:solid">  
  2.     <br />  
  3.     <div>  
  4.         <b>Select your Country:</b>  
  5.     </div>  
  6.   
  7.   
  8.     <div>  
  9.         @Html.DropDownList("country", ViewBag.country as List<SelectListItem>, new { style = "width: 200px;" })  
  10.         
  11.     </div>   
Save the project and run it. It will bind the data and will be shown as follows:



Similarly, add one more action method, which will take one parameter as a countrycode to retrieve the state of the respective country and adding jQuery method will send the selected country Id to the controller.

Here is jQuery code, which will send the Id and selected country id to the Action method and bind the data to the state drop down list.
  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  2. <script type="text/javascript">  
  3.   
  4.     $(document).ready(function () {  
  5.         
  6.         $("#country").change(function () {  
  7.             $("#State").empty();  
  8.             $.ajax({  
  9.                 type: 'POST',  
  10.                 url: '@Url.Action("getstate")',  
  11.   
  12.                 dataType: 'json',  
  13.   
  14.                 data: { id: $("#country").val() },  
  15.   
  16.   
  17.                 success: function (states) {  
  18.   
  19.   
  20.                     $.each(states, function (i, state) {  
  21.                         $("#State").append('<option value="' + state.Value + '">' +  
  22.                              state.Text + '</option>');  
  23.   
  24.                     });  
  25.                 },  
  26.                 error: function (ex) {  
  27.                     alert('Failed to retrieve country states.' + ex);  
  28.                 }  
  29.             });  
  30.             return false;  
  31.         })  
  32.     });  
  33.   
  34. </script>   
Now, it is the getstate controller.
  1. public JsonResult getstate(int id)  
  2.        {  
  3.            string countrystring = "select * from tbl_state where countrycode='"+id+"'";  
  4.              
  5.          
  6.            DataTable dt = new DataTable();  
  7.            dt = objdal.MyMethod(countrystring);  
  8.            List<SelectListItem> list = new List<SelectListItem>();  
  9.            list.Add(new SelectListItem { Text = "--Select Country--", Value = "0" });  
  10.            foreach (DataRow row in dt.Rows)  
  11.            {  
  12.   
  13.                list.Add(new SelectListItem { Text = Convert.ToString(row.ItemArray[1]), Value = Convert.ToString(row.ItemArray[0]) });  
  14.   
  15.            }  
  16.            return Json(new SelectList(list, "Value""Text", JsonRequestBehavior.AllowGet));  
  17.   
  18.   
  19.        }  
Here, is the view:
  1. <div style=" background-color:blanchedalmond; border-color:black; border:solid">  
  2.   
  3.   
  4.     <div>  
  5.         <b>Select Country</b>  
  6.     </div>  
  7.     <div>  
  8.         @Html.DropDownList("country", ViewBag.country as List<SelectListItem>, new { style = "width: 200px;" })  
  9.   
  10.     </div>  
  11.     <br />  
  12.   
  13.     <div>  
  14.         <b>Select State</b>  
  15.     </div>  
  16.     <div>  
  17.         @Html.DropDownList("State"new SelectList(string.Empty, "Value""Text"), "--Select State--"new { style = "width:200px" })  
  18.     </div>  
  19.    </div>   


 Similarly, pass the state Id to the controller, using jQuery, and get all the cities from the controller and bind, using the drop down list. 
  1. <script type="text/javascript">  
  2.   
  3.     $(document).ready(function () {  
  4.           
  5.         $("#State").change(function () {  
  6.             $("#city").empty();  
  7.             $.ajax({  
  8.                 type: 'POST',  
  9.                 url: '@Url.Action("getCity")',  
  10.                 dataType: 'json',  
  11.                 data: { id: $("#State").val() },  
  12.                 success: function (city) {  
  13.   
  14.                     $.each(city, function (i, city) {  
  15.                         $("#city").append('<option value="'  
  16.                                                    + city.Value + '">'  
  17.                                              + city.Text + '</option>');  
  18.                     });  
  19.                 },  
  20.                 error: function (ex) {  
  21.                     alert('Failed.' + ex);  
  22.                 }  
  23.             });  
  24.             return false;  
  25.         })  
  26.     });  
  27. </script>  
Now, here is the Action method.
  1. public JsonResult getCity(int id)  
  2.       {  
  3.           string countrystring = "select * from tbl_city where statecode='" + id + "'";  
  4.           DataSet ds = new DataSet();  
  5.           List<string> li = new List<string>();  
  6.           DataTable dt = new DataTable();  
  7.           dt = objdal.MyMethod(countrystring);  
  8.           List<SelectListItem> list = new List<SelectListItem>();  
  9.           foreach (DataRow row in dt.Rows)  
  10.           {  
  11.   
  12.               list.Add(new SelectListItem { Text = Convert.ToString(row.ItemArray[1]), Value = Convert.ToString(row.ItemArray[0]) });  
  13.   
  14.           }  
  15.           return Json(new SelectList(list, "Value""Text", JsonRequestBehavior.AllowGet));  
  16.   
  17.   
  18.       }  
Now, here is my complete view.
  1. @{  
  2.     ViewBag.Title = "Region Details";  
  3. }  
  4.   
  5. <h2>Details</h2>  
  6.   
  7. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  8.   
  9.   
  10. <script type="text/javascript">  
  11.     $(document).ready(function () {  
  12.        
  13.         $("#country").change(function () {  
  14.             $("#State").empty();  
  15.             $.ajax({  
  16.                 type: 'POST',  
  17.                 url: '@Url.Action("getstate")',  
  18.   
  19.                 dataType: 'json',  
  20.   
  21.                 data: { id: $("#country").val() },  
  22.   
  23.   
  24.                 success: function (states) {  
  25.   
  26.   
  27.                     $.each(states, function (i, state) {  
  28.                         $("#State").append('<option value="' + state.Value + '">' +  
  29.                              state.Text + '</option>');  
  30.   
  31.                     });  
  32.                 },  
  33.                 error: function (ex) {  
  34.                     alert('Failed to retrieve states.' + ex);  
  35.                 }  
  36.             });  
  37.             return false;  
  38.         })  
  39.     });  
  40. </script>  
  41. <script type="text/javascript">  
  42.   
  43.     $(document).ready(function () {  
  44.           
  45.         $("#State").change(function () {  
  46.             $("#city").empty();  
  47.             $.ajax({  
  48.                 type: 'POST',  
  49.                 url: '@Url.Action("getCity")',  
  50.                 dataType: 'json',  
  51.                 data: { id: $("#State").val() },  
  52.                 success: function (city) {  
  53.   
  54.                     $.each(city, function (i, city) {  
  55.                         $("#city").append('<option value="'  
  56.                                                    + city.Value + '">'  
  57.                                              + city.Text + '</option>');  
  58.                     });  
  59.                 },  
  60.                 error: function (ex) {  
  61.                     alert('Failed.' + ex);  
  62.                 }  
  63.             });  
  64.             return false;  
  65.         })  
  66.     });  
  67. </script>  
  68.   
  69.   
  70. <div style=" background-color:blanchedalmond; border-color:black; border:solid">  
  71.     <br />  
  72.     <div>  
  73.         <b>Select your Country:</b>  
  74.     </div>  
  75.   
  76.   
  77.     <div>  
  78.         @Html.DropDownList("country", ViewBag.country as List<SelectListItem>, new { style = "width: 200px;" })  
  79.         
  80.     </div>  
  81.     <br />  
  82.     <div>  
  83.         <b>Select your State:</b>  
  84.     </div>  
  85.   
  86.     <div>  
  87.   
  88.     </div>  
  89.     <div>  
  90.   
  91.         @Html.DropDownList("State"new SelectList(string.Empty, "Value""Text"), "--Select State--"new { style = "width:200px" })  
  92.   
  93.     </div>  
  94.     <br />  
  95.     <div>  
  96.        <b>Select your Region:</b>   
  97.     </div>  
  98.   
  99.     <div>  
  100.   
  101.         @Html.DropDownList("city"new SelectList(string.Empty, "Value""Text"), "--Select City--"new { style = "width:200px" })  
  102.   
  103.     </div>  
  104.       
  105.   
  106.          
  107.           
  Finally, we get the output as follows:



Using Entity frame work: 
Here, I will show how to achieve cascading drop down list, using Entity frame work in MVC:
 
The complete controller code is given:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MVC_Project.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         CodeXEntities obj = new CodeXEntities();  
  12.         public ActionResult Index()  
  13.         {  
  14.             return View();  
  15.         }  
  16.   
  17.         public ActionResult About()  
  18.         {  
  19.             ViewBag.Message = "Your application description page.";  
  20.   
  21.             return View();  
  22.         }  
  23.   
  24.         public ActionResult Contact()  
  25.         {  
  26.             ViewBag.Message = "Your contact page.";  
  27.   
  28.             return View();  
  29.         }  
  30.         public ActionResult Details()  
  31.         {  
  32.               
  33.             var country = obj.tbl_Country.ToList();  
  34.             List<SelectListItem> li = new List<SelectListItem>();  
  35.             li.Add(new SelectListItem { Text = "--Select Country--", Value = "0" });  
  36.              
  37.             foreach(var m in country)  
  38.             {  
  39.   
  40.                   
  41.                 li.Add(new SelectListItem { Text = m.Country, Value = m.slNO.ToString() });  
  42.                 ViewBag.country = li;  
  43.                   
  44.             }  
  45.             return View();  
  46.         }  
  47.   
  48.         public JsonResult getstate(int id)  
  49.         {  
  50.             var states = obj.tbl_state.Where(x => x.countryCode == id).ToList();  
  51.             List<SelectListItem> listates = new List<SelectListItem>();  
  52.   
  53.             listates.Add(new SelectListItem { Text = "--Select State--", Value = "0" });  
  54.             if (states != null)  
  55.             {  
  56.                 foreach(var x in states)  
  57.                 {  
  58.                       listates.Add(new SelectListItem { Text =x.State, Value =x.SlNo.ToString() });  
  59.   
  60.                 }  
  61.   
  62.                 
  63.   
  64.             }  
  65.   
  66.   
  67.             return Json(new SelectList(listates, "Value""Text", JsonRequestBehavior.AllowGet));  
  68.         }  
  69.   
  70.         public JsonResult getCity(int id)  
  71.         {  
  72.             var city = obj.tbl_city.Where(x => x.statecode == id).ToList();  
  73.             List<SelectListItem> licity = new List<SelectListItem>();  
  74.   
  75.             licity.Add(new SelectListItem { Text = "--Select City--", Value = "0" });  
  76.             if (city != null)  
  77.             {  
  78.                 foreach (var l in city)  
  79.                 {  
  80.                     licity.Add(new SelectListItem { Text = l.District, Value = l.SlNo.ToString() });  
  81.   
  82.                 }  
  83.   
  84.   
  85.   
  86.             }  
  87.   
  88.   
  89.             return Json(new SelectList(licity, "Value""Text", JsonRequestBehavior.AllowGet));  
  90.         }  
  91.   
  92.        
  93.     }  
  94. }  
 The complete view is:
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>Index</h2>  
  6. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  7. <script type="text/javascript">  
  8.   
  9.     $(document).ready(function () {  
  10.         
  11.         $("#country").change(function () {  
  12.             $("#State").empty();  
  13.             $.ajax({  
  14.                 type: 'POST',  
  15.                 url: '@Url.Action("getstate")',  
  16.   
  17.                 dataType: 'json',  
  18.   
  19.                 data: { id: $("#country").val() },  
  20.   
  21.   
  22.                 success: function (states) {  
  23.   
  24.   
  25.                     $.each(states, function (i, state) {  
  26.                         $("#State").append('<option value="' + state.Value + '">' +  
  27.                              state.Text + '</option>');  
  28.   
  29.                     });  
  30.                 },  
  31.                 error: function (ex) {  
  32.                     alert('Failed to retrieve states.' + ex);  
  33.                 }  
  34.             });  
  35.             return false;  
  36.         })  
  37.     });  
  38.   
  39. </script>  
  40.   
  41. <script type="text/javascript">  
  42.   
  43.     $(document).ready(function () {  
  44.        
  45.         $("#State").change(function () {  
  46.             $("#city").empty();  
  47.             $.ajax({  
  48.                 type: 'POST',  
  49.                 url: '@Url.Action("getcity")',  
  50.                 dataType: 'json',  
  51.                 data: { id: $("#State").val() },  
  52.                 success: function (city) {  
  53.   
  54.                     $.each(city, function (i, city) {  
  55.                         $("#city").append('<option value="'  
  56.                                                    + city.Value + '">'  
  57.                                              + city.Text + '</option>');  
  58.                     });  
  59.                 },  
  60.                 error: function (ex) {  
  61.                     alert('Failed.' + ex);  
  62.                 }  
  63.             });  
  64.             return false;  
  65.         })  
  66.     });  
  67. </script>  
  68. <div style=" background-color:aqua; border-color:black; border:solid">  
  69.   
  70.   
  71.     <div>  
  72.         <b>Select Country</b>  
  73.     </div>  
  74.     <div>  
  75.         @Html.DropDownList("country", ViewBag.country as List<SelectListItem>, new { style = "width: 200px;" })  
  76.   
  77.     </div>  
  78.     <br />  
  79.   
  80.     <div>  
  81.         <b>Select State</b>  
  82.     </div>  
  83.     <div>  
  84.         @Html.DropDownList("State"new SelectList(string.Empty, "Value""Text"), "--Select State--"new { style = "width:200px" })  
  85.     </div>  
  86.      
  87.     <br />  
  88.     <div>  
  89.         <b>Select Region</b>  
  90.     </div>  
  91.     <div>  
  92.   
  93.         @Html.DropDownList("city"new SelectList(string.Empty, "Value""Text"), "--Select City--"new { style = "width:200px" })  
  94.   
  95.     </div>  
  96.   
  97. </div>  
Here is the result, as shown:

Thus, in this way, we can achieve cascading drop down list in our project.

Up Next
    Ebook Download
    View all
    Learn
    View all