How to update a second dropdown based on the selection of first dropdown selection?

后端 未结 1 1591
梦谈多话
梦谈多话 2020-12-12 06:18

I have two DropDownListFor helpers and the SelectList for the second one depends on the selected value from the first one.

So, what I need to do is: when the user ch

相关标签:
1条回答
  • 2020-12-12 06:32

    You need to listen to the change event of your first dropdown, read the selected value and make an ajax request to the server with this value. Have action method which accepts this value and return the data for your second dropdown. In your ajax call's callback, read the json data coming back, look through it and populate the second dropdown.

    Assuming your form has 2 dropdowns, one for Countries and one for States

    $(function(){
    
      $("#Country").change(function(){
    
         var countryId = $(this).val();
         var url = "@Url.Action("GetStates,"Country")"+countryId;
    
         $.getJSON(url,function(data){
    
             var options="";
             $.each(data,function(a,b){
               options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
             });        
             $("#State").html(options);
         });
    
      });
    
    });
    

    Assuming GetStates action method in CountryController accepts a country Id and return a list of items (with a Value and Text property) for the states belongs to the selected country.

    public ActionResult GetStates(int id)
    {
       var dummyStates = new List<SelectListItem>
       {
         new SelectListItem { Value="1", Text="Michigan"},
         new SelectListItem { Value="2", Text="Florida"},
         new SelectListItem { Value="3", Text="Seattle"}
       };
       return Json(dummyStates,JsonRequestBehaviour.AllowGet);
    }
    
    0 讨论(0)
提交回复
热议问题