Hi comunidadmexi...,
Using this below article i have created the example.
Check this example. Now please take its reference and correct your code.
Model
public class CascadingModel
{
public CascadingModel()
{
this.Countries = new List<SelectListItem>();
this.States = new List<SelectListItem>();
this.Cities = new List<SelectListItem>();
}
public List<SelectListItem> Countries { get; set; }
public List<SelectListItem> States { get; set; }
public List<SelectListItem> Cities { get; set; }
public int CountryId { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
}
Namespaces
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
CascadingModel model = new CascadingModel();
model.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
return View(model);
}
[HttpPost]
public JsonResult AjaxMethod(string type, int value)
{
CascadingModel model = new CascadingModel();
switch (type)
{
case "CountryId":
model.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + value, "StateName", "StateId");
break;
case "StateId":
model.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + value, "CityName", "CityId");
break;
}
return Json(model);
}
[HttpPost]
public ActionResult Index(int countryId, int stateId, int cityId)
{
CascadingModel model = new CascadingModel();
model.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
model.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
model.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
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;
}
}
View
@model Cascading_DropDownList_MVC.Models.CascadingModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
.modalBackground {
position: fixed;
top: 0;
left: 0;
background-color: black;
z-index: 99;
opacity: 0.8;
filter: alpha(opacity=80);
-moz-opacity: 0.8;
min-height: 100%;
width: 100%;
}
.loading {
font-family: Arial;
font-size: 10pt;
border: 5px solid #67CFF5;
width: 200px;
height: 100px;
display: none;
position: fixed;
background-color: White;
z-index: 999;
}
</style>
</head>
<body>
<div class="loading" align="center">
Loading. Please wait.<br /><br />
<img alt="" src="~/Images/loader.gif" />
</div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownListFor(m => m.CountryId, Model.Countries, "Please select")
<br />
<br />
@Html.DropDownListFor(m => m.StateId, Model.States, "Please select")
<br />
<br />
@Html.DropDownListFor(m => m.CityId, Model.Cities, "Please select")
<br />
<br />
<input type="submit" value="Submit" />
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$(".loading").hide();
$("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");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: ' + value + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#StateId");
DisableDropDown("#CityId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", 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) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
$(function () {
if ($("#CountryId").val() != "" && $("#StateId").val() != "" && $("#CityId").val() != "") {
var message = "Country: " + $("#CountryId option:selected").text();
message += "\nState: " + $("#StateId option:selected").text();
message += "\nCity: " + $("#CityId option:selected").text();
alert(message);
}
});
</script>
</body>
</html>
Screenshot