Abdalla Omran

Abdalla Omran

  • NA
  • 334
  • 32k

Getting undefined in Cascading DropDownList In ASP.Core MVC

Jul 11 2019 2:33 PM
In the first DropdownList should display the Countries and in the second should display Cities based on the Country like .. USA then display just cities in USA . well i am getting undefined in dropdown city the Question is why i am getting always undefined in City dropDown list ?
here is countrol :
 public ActionResult Index()
{
Details();
return View();
}
public void Details (
{
var model = db.GetUniversities().ToList();
List<SelectListItem> li = new List<SelectListItem>();
 
li.Add(new SelectListItem { Text = "Please select Country",Value="0"});
 
foreach (var item in model)
{
li.Add(new SelectListItem { Text = item.Country, Value = item.Id.ToString()});
ViewBag.state = li;
}
[HttpPost]
public JsonResult GetCity (int id)
{
var ddlCity = db.GetUniversities().Where(x => x.Id == id).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
//licities.Add(new SelectListItem { Text = "--Select City--", Value = "0" });
if (ddlCity != null)
{
 
foreach (var x in ddlCity)
{
licities.Add(new SelectListItem { Text = x.City, Value = x.Id.ToString() });
}
}
return Json(new SelectList(licities, "Text", "Value"));
}
here view
 
<div class="form-group">
@Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Country, ViewBag.state as List<SelectListItem>, new { style = "width: 200px;" })
@Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.City, new SelectList(string.Empty, "Value", "Text"), "--Select City--", new { style = "width:200px" })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })</pre>
here jQuery
$(document).ready(function () {
$("#Country").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#Country").val() },
success: function (city) {
$.each(city, function (i, city) {
$("#City").append('<option value="' + city.Value + '">'+ city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});

Answers (1)