如何根据第一个下拉列表的选择更新第二个下拉列表? [英] How to update a second dropdown based on the selection of first dropdown selection?

查看:119
本文介绍了如何根据第一个下拉列表的选择更新第二个下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个DropDownListFor帮助器,第二个SelectList取决于第一个选择的值。



所以,我需要做的是:用户从第一个DropDownListFor帮助器中选择一个值,第二个DropDownListFor帮助器的SelectList必须用适当的值更新。



如何使用jQuery更新此SelectList?

解决方案

您需要收听第一个下拉菜单中的更改 ,读取所选值并使用此值向服务器发出ajax请求。具有接受此值并返回第二个下拉列表的数据的操作方法。在你的ajax电话的回调中,阅读回来的json数据,看看它并填写第二个下拉列表。



假设你的表单有2个下拉列表,一个是国家的,一个是国家

  $(function(){

$(#Country)。change (){

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

});

});
pre>

假设 GetStates 中的操作方法CountryController 接受国家/地区ID,并返回一个列表(具有Value和Text属性),州属于所选国家。

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


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?

解决方案

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

这篇关于如何根据第一个下拉列表的选择更新第二个下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆