Description:
Model:
In
this example we explain that how to Bind Country,State,City Dropdown List based
on selection using jQuery Ajax in Asp.Net MVC.or Cascading Country State
DropDownList using jQuery AJAX in ASP.Net MVC Razor. Or how to populate or bind
DropDownList using jQuery Ajax in Asp.Net MVC Razor. Or how to Cascading or
dependent country, state dropdown list in mvc razor.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
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; }
}
Controller:
public class EmployeeController : Controller
{
// GET: Employee
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>
</head>
<body>
@using (Html.BeginForm("Index", "Employee", 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 () {
$("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: "/Employee/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) {
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>
0 comments:
Post a Comment