Hello everyone,
I'm fairly new to MVC/Javascript and have been experimenting with different tutorials in order to create a cascading drop down list for selecting State and City on an MVC view. In my latest attempt, I followed this example.
While the states populate from the database successfully, the cities dropdown remains blank with about 10 empty spaces, regardless of the state selected. Can anyone point out what I might be missing? Any advice or feedback is greatly appreciated!
Here is some information about the database tables:
- Regions (contains states): Id (Primary Key Int), Name (Varchar(255) state/regionname), CountryId (Int)
- Cities (Contains cities): Id (Primary Key Int), Name (Varchar(255) city/name), RegionID (int, linked to region table)
Here is the view model:
public class UserAds
{
public int addId { get; set; }
public int userCreatedAcctId { get; set; }
public string userForAccEmail { get; set; }
public string photoFileLocation { get; set; }
public string addTitle { get; set; }
public string addDesc { get; set; }
public string addPersonalityTraits { get; set; }
public string addHobbies { get; set;}
[Required]
[Display(Name = "State / Region")]
public int stateId { get; set; }
[Required]
[Display(Name = "City")]
public int cityId { get; set; }
}
Here is the controller:
[HttpGet]
public ActionResult CreateAd()
{
List<Region> stateList = db.Regions.ToList();
ViewBag.StateList = new SelectList(stateList, "Id", "Name");
return View();
}
public JsonResult GetCitiesList(int StateId)
{
db.Configuration.ProxyCreationEnabled = false;
List<City> CityList = db.Cities.Where(x => x.RegionId == StateId).ToList();
return Json(CityList, JsonRequestBehavior.AllowGet);
}
The view:
<div class="container">
<div class="form-group">
@if (ViewBag.StateList != null)
{
@Html.DropDownListFor(model => model.stateId, ViewBag.StateList as SelectList, "--Select State--", new { @class = "form-control" })
}
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.cityId, new SelectList(" "), "--Select City--", new { @class = "form-control" })
</div>
Javascript Code:
<script>
$(document).ready(function () {
$("#stateId").change(function () {
$.get("GetCitiesList", { StateId: $("#stateId").val() }, function (data) {
$("#cityId").empty();
$.each(data, function (index, row) {
$("#cityId").append("<option value=" + row.Id + "'>" + row.Name + "</option>")
});
});
})
});
To debug JavaScript code in Internet Explorer, you can use this Javascript debugger.