Cascading dropdown using Ajax in MVC

Cascading dropdown using Ajax in MVC application is explained in this article. The cascading dropdown will be populated from database using javascript ajax. Add three table named City,Town and Village. The script to create and insert data in database is given below.

Download Script

Model

public class Cascading
   {
       public Cascading()
   {
       this.Cities = new List<SelectListItem>();
       this.Towns = new List<SelectListItem>();
       this.Villages = new List<SelectListItem>();
   }

   public List<SelectListItem> Cities { get; set; }
   public List<SelectListItem> Towns { get; set; }
   public List<SelectListItem> Villages { get; set; }

   public int CityID { get; set; }
   public int TownID { get; set; }
   public int VillageID { get; set; }
   }

Home Controller

// GET: Home
       public ActionResult Index()
       {
           Cascading model = new Cascading();
           model.Cities = PopulateDropDown("SELECT CityID, CityName FROM AddCity", "CityName", "CityID");
           return View(model);
       }

       [HttpPost]
       public JsonResult AjaxMethod(string type, int value)
       {
           Cascading model = new Cascading();
           switch (type)
           {
               case "TownID":
                   model.Towns = PopulateDropDown("SELECT TownID, TownName FROM AddTown WHERE CityID = " + value, "TownName", "TownID");
                   break;
               case "VillageID":
                   model.Villages = PopulateDropDown("SELECT VillageID, VillageName FROM AddVillage WHERE TownID = " + value, "VillageName", "VillageID");
                   break;
           }
           return Json(model);
       }

       [HttpPost]
       public ActionResult Index(int pCityid, int pTownid, int pVillageid)
       {
           Cascading model = new Cascading();
           model.Cities = PopulateDropDown("SELECT CityID, CityName FROM AddCity", "CityName", "CityID");
           model.Towns = PopulateDropDown("SELECT TownID, TownName FROM AddTown WHERE CityID = " + pCityid, "TownName", "TownID");
           model.Villages = PopulateDropDown("SELECT VillageID, VillageName FROM AddVillage WHERE TownID = " + pTownid, "VillageName", "VillageID");
           return View(model);
       }

       private static List<SelectListItem> PopulateDropDown(string query, string textColumn, string valueColumn)
       {
           List<SelectListItem> items = new List<SelectListItem>();
           string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
           using (SqlConnection con = new SqlConnection(constr))
           {
               using (SqlCommand cmd = new SqlCommand(query))
               {
                   cmd.Connection = con;
                   con.Open();
                   using (SqlDataReader sdr = cmd.ExecuteReader())
                   {
                       while (sdr.Read())
                       {
                           items.Add(new SelectListItem
                           {
                               Text = sdr[textColumn].ToString(),
                               Value = sdr[valueColumn].ToString()
                           });
                       }
                   }
                   con.Close();
               }
           }

           return items;
       }

Index View

@model MVC_demo_applications.Models.Cascading
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.DropDownListFor(m => m.CityID, Model.Cities, "Please select")
        <br/>
        <br/>
        @Html.DropDownListFor(m => m.TownID, Model.Towns, "Please select")
        <br/>
        <br/>
        @Html.DropDownListFor(m => m.VillageID, Model.Villages, "Please select")
        <br/>
        <br/>
        <input type="submit" value="Submit"/>
    }
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("select").each(function () {
                if ($(this).find("option").length <= 1) {
                    $(this).attr("disabled", "disabled");
                }
            });
 
            $("select").change(function () {
                var value = 0;
                if ($(this).val() != "") {
                    value = $(this).val();
                }
                var id = $(this).attr("id");
                debugger;
                $.ajax({
                    type: "POST",
                    url: "~/Home/AjaxMethod",
                    data: "{'type':'" + id + "','value':'" + value + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data) {
                            var dropDownId;
                            var list;
                            switch (id) {
                                case "CityID":
                                    list = response.Towns;
                                    DisableDropDown("#TownID");
                                    DisableDropDown("#VillageID");
                                    PopulateDropDown("#TownID", list);
                                    break;
                                case "TownID":
                                    dropDownId = "#VillageID";
                                    list = response.Villages;
                                    DisableDropDown("#VillageID");
                                    PopulateDropDown("#VillageID", list);
                                    break;
                            }
                        }
                       
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
 
        function DisableDropDown(dropDownId) {
            $(dropDownId).attr("disabled", "disabled");
            $(dropDownId).empty().append('<option selected="selected" value="0">Please select</option>');
        }
 
        function PopulateDropDown(dropDownId, list) {
            if (list != null && list.length > 0) {
                $(dropDownId).removeAttr("disabled");
                $.each(list, function () {
                    $(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        }
 
        $(function () {
            if ($("#CityID").val() != "" && $("#TownID").val() != "" && $("#VillageID").val() != "") {
                var message = "City: " + $("#CityID option:selected").text();
                message += "\nTown: " + $("#TownID option:selected").text();
                message += "\nVillage: " + $("#VillageID option:selected").text();
                alert(message);
            }
        });
    </script>
</body>
</html>

Output