-1

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.

screenshot

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.');
            }
        });
    });
});

mmcc88
  • 177
  • 1
  • 10
  • It's simple! Try to make a different AJAX call when selecting your "Region" dropdown and show the values inside your "District" dropdown. – Ashraf.Shk786 Feb 14 '17 at 09:10
  • @Ashraf.Shk786 Not really sure how to make the ` – mmcc88 Feb 14 '17 at 09:51
  • There are multiple problems with your implementation and you have not even shown the view code, and I suggest you look at [this DotNetFiddle](https://dotnetfiddle.net/1bPZym) –  Feb 14 '17 at 10:19
  • @StephenMuecke Thanks for the link. I've just figured out how to do it. Please feel free to comment on it. However, the view is just simply ``. The javascript (posted above) that I used in the view is more important for the question I think. – mmcc88 Feb 14 '17 at 12:17
  • Strongly suggest you study the link I gave you (you might think your self answer will solve your immediate problem but its bad and is not addressing all the other issues you have) –  Feb 15 '17 at 02:12

1 Answers1

0

I have no idea why there is someone votes -ve for my question rather than offering help or idea. Anyway I figure out a way to solve it. Hope this could help someone else.

In the javascript I simply get the DistrictID from the Model that passed to the view.

var selectedDistrict = @Model.DistrictID;

Then in the $.each function I make a conditional statement to make the saved district as selected:

$.each(data, function (id, option) {
    if (option.id == selectedDistrict) {
        ddlDistrict.append($('<option selected="selected"></option>').val(option.id).html(option.name));
    } else {
        ddlDistrict.append($('<option></option>').val(option.id).html(option.name));
    }
});

Then it works like a charm.

mmcc88
  • 177
  • 1
  • 10
  • Nice work @Matt this will definitely help someone in future. And, people who have voted down for your question I think He/She thinks that question is not guinine or its a simple question where you can find solutions on your own. So, no worries don't take it in a wrong way just try your level best with different possibilities to find solutions before you post anything on the community. Thanks to such peoples it's because of them you were able to do it by yourself and Ofcourse your hardwork :-) – Ashraf.Shk786 Feb 15 '17 at 11:24