I got a cascading dropdown list in my "Create" view, which after the first dropdown #regions
is selected, the second dropdown #districts
will render a list of districts in that region.
How can I return the "District" value from the DB to the #districts
dropdown list in the "Edit" view when it is first loaded? I can only have my Region value showing, but blank for District value.
The problem of my code is that the "District" dropdown list is only populated when the "Region" dropdown list is changed/selected.
I searched through a lot of post about this but all of them are talking about how to make a cascading dropdown list, but not displaying data from DB.
In Edit controller:
var item = await _context.Items
.Include(i => i.District)
.SingleOrDefaultAsync(i => i.ID == id);
var model = new ViewModel { Title = item.Title, RegionID = item.District.RegionID, DistrictID = item.DistrictID };
List<Region> regions = new List<Region>();
regions = await _context.Regions.ToListAsync();
regions.Insert(0, new Region { ID = 0, Name = "-- Select a region --" });
List<District> districts = new List<District>();
ViewBag.RegionList = new SelectList(regions, "ID", "Name");
ViewBag.DistrictList = new SelectList(districts, "ID", "Name");
return View(model);
In Edit View:
<script type="text/javascript">
$(function () {
if ($("#regions").val() == '0') {
var districtDefaultValue = "<option value=''>-- Select a district --</option>";
$("#districts").html(districtDefaultValue).show();
}
$("#regions").change(function () {
var selectedItemValue = $(this).val();
var ddlDistrict = $("#districts");
$.ajax({
cache: false,
type: "GET",
url: '@Url.Action("GetDistrictByRegionId", "Items")',
data: { "id": selectedItemValue },
success: function (data) {
ddlDistrict.html('');
$.each(data, function (id, option) {
ddlDistrict.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error occurred in loading corresponding districts.');
}
});
});
});