How to update a second dropdown based on the selec

2019-03-03 23:43发布

问题:

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 chooses a value from the first DropDownListFor helper, the SelectList for the second DropDownListFor helper has to be updated with proper values.

How can I update this SelectList with jQuery?

回答1:

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