Hi comunidadmexi...,
Using the below article i have created the example.
Check this example. Now please take its reference and correct your code.
Model
using System.ComponentModel.DataAnnotations;
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; }
[Required(ErrorMessage = "Country Required!")]
public int CountryId { get; set; }
[Required(ErrorMessage = "State Required!")]
public int StateId { get; set; }
[Required(ErrorMessage = "City Required!")]
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(CascadingModel model)
{
model.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
model.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + model.CountryId, "StateName", "StateId");
model.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + model.StateId, "CityName", "CityID");
if (ModelState.IsValid)
{
return View(model);
}
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>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownListFor(m => m.CountryId, Model.Countries, "Please select")
@Html.ValidationMessageFor(m => m.CountryId, "", new { @class = "text-danger" })
<br />
<br />
@Html.DropDownListFor(m => m.StateId, Model.States, "Please select")
@Html.ValidationMessageFor(m => m.StateId, "", new { @class = "text-danger" })
<br />
<br />
@Html.DropDownListFor(m => m.CityId, Model.Cities, "Please select")
@Html.ValidationMessageFor(m => m.CityId, "", new { @class = "text-danger" })
<br />
<br />
<input type="submit" value="Submit" />
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.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");
$.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;
}
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">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 ($("#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