Cascading Dropdown With Jquery
1)First Create tables
2)In controllr write this code
public class AddressController : Controller
{
ContactInfoEntities db = new ContactInfoEntities();
public ActionResult Index()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryID", "Name");
return View();
}
public JsonResult GetStateList(int CountryId)
{
db.Configuration.ProxyCreationEnabled = false;
List<City> StateList = db.Cities.Where(x => x.CountryID == CountryId).ToList();
return Json(StateList, JsonRequestBehavior.AllowGet);
}
}
3)After this write this code in view
@model CascadingJqueryPractice.Models.Address
<br /><br />
<div class="container">
<div class="form-group">
@if (ViewBag.CountryList != null)
{
@Html.DropDownListFor(model => model.CountryID, ViewBag.CountryList as SelectList, "--Select Country--", new { @class = "form-control" })
}
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.CityID, new SelectList(" "), "--Select State--", new { @class = "form-control" })
</div>
</div>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryID").change(function () {
var CountryID = $(this).val();
$.get("/Address/GetStateList", { CountryId: CountryID }, function (data) {
$("#CityID").empty();
var item;
$.each(data, function (i, item) {
$('#CityID').append($('<option>', {
value: item.CityID,
text: item.Name
}));
});
});
})
});
</script>
Share This with your friend by choosing any social account