locked
How to fill the second dropdown on the selection of first dropdown RRS feed

  • Question

  • User-997500692 posted

    Hi. I want to implement to dropdowns by which if I choose one item from the first selectList (Region) then the related data will populate in the second selectlist (Zone). The first one keeps Regions data and the second selectList keeps related zones. For doing this, I implemented following code:

    public class OperatorViewModel {
     public IEnumerable<BuyWasteRequestViewModel> BuyWasteRequestVM { get; set; }
     [Required] public string SelectedRegionID { get; set; }
     [Required]
     public string SelectedZoneID { get; set; }
     public string SelectedRegionText { get; set; }
     public string SelectedZoneText { get; set; } 
    }





    In my controller, there is a method that sends the related zones to ajax in razor  
    public class OperatorController : Controller
        {
            private readonly WasteAPIContext _context;
    
            public OperatorController(WasteAPIContext context)
            {
                _context = context;
            }
    
     [HttpPost]
            public IActionResult Index(OperatorViewModel buywastervm)
            {
                
                return BuildIndexModel(buywastervm.SelectedRegionID, buywastervm.SelectedRegionText, buywastervm.SelectedZoneID, buywastervm.SelectedZoneText);
            }
    
    public IActionResult BuildIndexModel(string selectedRegionID, string selectedRegionText,string selectedZoneID, string selectedZoneText){
     ViewData["RegionId"] = new SelectList(_context.Region, "Id", "Name", "select");
    
     ViewData["ZoneId"] = new SelectList(_context.Zone.Where(c => c.RegionId == selectedZoneID), "Id", "Name", "select");
    
     OperatorVM.BuyWasteRequestVM = bwrvm;
                OperatorVM.SelectedRegionID = selectedRegionID;
                OperatorVM.SelectedRegionText = selectedRegionText;
                OperatorVM.SelectedZoneID = selectedZoneID;
                OperatorVM.SelectedZoneText = selectedZoneText;
    
      return View(OperatorVM);
     }
    
    public JsonResult GetZones(string ID)
            {
                
                 List<SelectListItem> ZoneList = new List<SelectListItem>();
    
                var zones = _context.Zone.Where(c => c.RegionId == ID).Select(c => new
                {
                    Value = c.Id,
                    Text = c.Name
                }).ToList();
    
                foreach (var item in zones)
                {
                    SelectListItem slist = new SelectListItem();
                    slist.Value = item.Value; /*0 + mvalue*/
                    slist.Text = item.Text;
                    ZoneList.Add(slist);
                }
    
    
                ViewData["ZoneId"] = new SelectList(_context.Zone.Where(c => c.RegionId == ID), "Id", "Name", "select");
                return Json(ZoneList);
    
            }
    
    }
    

    And here is my code in Index view:

    @model MyProject.ViewModels.OperatorViewModel
    
     <form method="post">
    @Html.DropDownListFor(m => m.SelectedRegionID, (IEnumerable<SelectListItem>)ViewBag.RegionId, "select", new { @style = "; width: 42%; padding: 2%; border: 1px solid #ced4da; border-radius: 3px; right: 4.5rem; height: 2.35rem;" })
                            @Html.HiddenFor(m => m.SelectedRegionText)
    
    
    <select id="SelectedZoneID" name="@Html.NameFor(c=>c.SelectedZoneID)" class="form-control statesSelect" asp-items="@(new SelectList(@ViewBag.ZoneID,"Id", "Name"))">
                                    <option value='0'>select</option>
     </select>
                                @Html.HiddenFor(m => m.SelectedZoneText)
    </form>
    
    <script>
      jQuery(document).ready(function ($) {
        $("#SelectedRegionID")
                .change(function () {
    
                    var id = $(this).val();
                    $("#SelectedRegionText").attr("value", $("#SelectedRegionID option:selected").text());
                    $.getJSON('@Url.Action("GetZones", "Operator")/' + id, function (data) {
                        //delete the options of $("#SelectedZoneID") and add new options
                        $("#SelectedZoneID").empty();
                        $("#SelectedZoneID").append('<option value="0">select</option>');
                         $.each(data, function (value, text) {
                             $("#SelectedZoneID").append('<option value="' + text.value + '">' + text.text + '</option>');
                    });
            });
                });
    
    
            $("#SelectedZoneID").change(function () {
                $("#SelectedZoneText").attr("value", $("#SelectedZoneID option:selected").text());
            });
    
            $("#SelectedRegionID")
          .change(function() {
              $('#SelectedRegionText').val($(this).find("option:selected").text());
    
         });

    Now my problem is, I want after choosing my considering region from region selectlist and accordingly choosing an item from zone selectlist and then submitting the form, I have the ability to see all populated related zones to selected region displayed before submitting the form in zone selectlist. Right now, after submitting the form, I'm just able to see <select> item in zone selectlist. Moreover, I need after submitting the form, the user can see the selected item in zone list as the selected option. Now I can see the selected region in Region selectlist after submitting the form which I set its data in my model after submitting the form. I kindly appreciate of any help.



    Tuesday, October 6, 2020 12:53 PM

All replies

  • User-474980206 posted

    That is how selects work, they only post the selected value, not the option list. You should rebuild the list on post back.

    Tuesday, October 6, 2020 2:38 PM
  • User-997500692 posted

    Thank you for your reply. So how can I rebuild the list on post back?

    Tuesday, October 6, 2020 5:24 PM
  • User-474980206 posted

    you have the selected item values. just do the database queries again.

    Tuesday, October 6, 2020 5:58 PM