Hello All,
I am having trouble to get values according to CountryID, StateID into the City drop down list, here is my HomeController.cs class code :
public class HomeController : Controller
{
MVCDDEntities _entities = new MVCDDEntities();
public ActionResult Index()
{
ViewBag.Countries = _entities.Countries.ToList();
ViewBag.States = _entities.States.ToList();
ViewBag.Cities = _entities.Cities.ToList();
return View();
}
public IList<state> GetStates(int countryID)
{
return _entities.States.Where(c => c.CountryID == countryID).ToList();
}
public IList<city> GetCitis(int stateID)
{
return _entities.Cities.Where(c => c.StateID == stateID).ToList();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadStatesByCountryID(string countryID)
{
var stateList = this.GetStates(Convert.ToInt32(countryID));
var stateData = stateList.Select(c => new SelectListItem() {
Text = c.StateName,
Value = c.StateID.ToString(),
});
return Json(stateData,JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadCitiesByStateID(string stateID)
{
var cityList = this.GetCitis(Convert.ToInt32(stateID));
var cityData = cityList.Select(c => new SelectListItem()
{
Text = c.CityName,
Value = c.CityID.ToString(),
});
return Json(cityData, JsonRequestBehavior.AllowGet);
}
}
And here is my view code :
@model MVCCascading.MVCDDEntities
@{
ViewBag.Title = "Index";
}
<p>
@Html.DropDownListFor(Model => Model.Countries, new SelectList(ViewBag.Countries as System.Collections.IEnumerable, "CountryID", "CountryName"),
"Select a Country", new { id = "ddlCountry" })
</p>
<p>
@Html.DropDownListFor(Model => Model.States, new SelectList(Enumerable.Empty<SelectListItem>(), "StateID", "StateName"),
"Select a State", new { id = "ddlStates" })
</p>
<p>
@Html.DropDownListFor(Model => Model.Cities, new SelectList(Enumerable.Empty<SelectListItem>(), "CityID", "CityID"),
"Select a City", new { id = "ddlCities" })
</p>
@section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCountry").change(function () {
var countryID = $(this).val();
$.getJSON("../Home/LoadStatesByCountryID", { countryid: countryID },
function (stateData) {
var select = $("#ddlStates");
select.empty();
select.append('<option/>', {
value: 0,
text: "Select a State"
});
$.each(stateData, function (index, itemData) {
alert(stateData);
alert(itemData);
select.append('<option/>', {
value: item.Value,
text: itemData.Text
});
});
});
});
});
</script>
}
I am getting 0 values in state list?
Can anyone help me to get out of this?
Thanks