Hi leila398,
Check this example. Now please take its reference and correct your code.
Database
I hanve used two tables Countries and States are created with the following schema.
Countries Table
States Table
Model
public class CascadingModel
{
public int CountryId { get; set; }
public int StateId { get; set; }
public SelectList Countries { get; set; }
public SelectList States { 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 = new SelectList(PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId"), "Value", "Text");
model.States = new SelectList(PopulateDropDown("SELECT StateId, StateName FROM States", "StateName", "StateId"), "Value", "Text");
return View(model);
}
[HttpPost]
public JsonResult GetStates(string param)
{
CascadingModel model = new CascadingModel();
model.States = new SelectList(PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = '" + param + "'", "StateName", "StateId"), "Value", "Text");
return Json(model);
}
[HttpPost]
public ActionResult Index(int countryId, int stateId)
{
CascadingModel model = new CascadingModel();
model.Countries = new SelectList(PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId"), "Value", "Text");
model.States = new SelectList(PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId"), "Value", "Text");
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_DropDownListFor_Select2_MVC.Models.CascadingModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style>
select {
background-color: #fff;
border: 1px solid #aaa;
border-radius: 4px;
}
</style>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)Model.Countries, "Select", new { @class = "form-control" })
<br />
<br />
@Html.DropDownListFor(m => m.StateId, Enumerable.Empty<SelectListItem>(), "Select", new { @class = "form-control" })
<br />
<br />
<input type="submit" value="Submit" />
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script type="text/javascript">
$(function () {
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$('#CountryId').change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
$.ajax({
type: "POST",
url: "/Home/GetStates",
data: '{param: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var list = response.States;
$("#StateId").empty().append('<option selected="selected" value="0">Select</option>');
if (list != null && list.length > 0) {
$("#StateId").removeAttr("disabled");
$.each(list, function () {
$("#StateId").append($("<option></option>").val(this['Value']).html(this['Text']));
});
$("#StateId").select2();
}
},
error: function (response) {
alert(response.responseText);
}
});
});
});
$(function () {
if ($('#CountryId').val() == "") {
$("#StateId").prop("disabled", true);
}
if ($("#CountryId").val() != "" && $("#StateId").val() != "") {
var message = "Country: " + $("#CountryId option:selected").text();
message += "\nState: " + $("#StateId option:selected").text();
alert(message);
}
});
</script>
</body>
</html>
Screenshot