How to use cascading DropDown in MVC Razor
Model
namespace RegistrationForm.Models { public class UserDetailModel {[Display(Name = "CountryDetail")] public List<Country> CountryDetail; [Display(Name = "selectedcountry")] public string SelectedCountry { get; set; } [Display(Name = "stateDetail")] public List<State> StateDetail { get; set; } } public class Country { public int CountryId { get; set; } public string CountryName { get; set; } } public class State { public int StateId { get; set; } public string StateName { get; set; } } }Controller:
public class GettingTextInDDLController : Controller { public ActionResult Index() { var obj = new UserDetailModel(); obj.CountryDetail = new List<Country>() { new Country() { CountryId = 1, CountryName = "INDIA" }, new Country() { CountryId = 2, CountryName= "US" }, new Country() { CountryId = 3, CountryName= "Russia" }, new Country() { CountryId = 4, CountryName= "UK" } }; return View(obj); }public ActionResult FirstDdl(string selectedCountry) { var obj = new UserDetailModel(); if (selectedCountry == "INDIA") { obj.StateDetail = new List<State>() { new State() {StateId = 1, StateName = "Tamil Nadu"}, new State() {StateId = 2, StateName = "Karnataka"}, new State() {StateId = 3, StateName = "Delhi"}, new State() {StateId = 4, StateName = "J&K"} }; } else { //.... Bind states for other countries obj.StateDetail = new List<State>() { new State() {StateId = 1, StateName = "Others"}, }; } return Json(obj); } }View
use @model RegistrationForm.Models.UserDetailModel in the first line of view <script type="text/javascript"> function ddListChange() { $.ajax({ url: '@Url.Action("FirstDdl", "GettingTextInDDL")', data: { selectedCountry: $('#SelectedCountry option:selected').text() }, cache: false, type: "POST", success: function (data) { var parsedJsonData = data.StateDetail.length; var state = "<option value=`0`>Select City</option>"; for (var x = 0; x < parsedJsonData; x++) { state += "<option value=" + data.StateDetail[x]["StateId"] + ">" + data.StateDetail[x]["StateName"] + "</option>"; } $('#ddlstate').html(state).show(); }, error: function (reponse) { alert("error : " + reponse); } }); } </script> <table> <tr> <td id="tdcountry"> @Html.DropDownListFor(a => a.SelectedCountry, new SelectList(Model.CountryDetail, "CountryId", "CountryName"), new { onchange = "ddListChange()" }) </td> </tr> <tr> <td id="tdstate"> <select id="ddlstate" name="ddlstate" style="width: 200px"> <option>Select Country</option> </select> </td> </tr> </table>Output
Before Selecting Country:
After Selecting it will populate list of states belong to Country India