2012-02-05 96 views
1

我想设计一个级联下拉框。我正在使用3个asp.net下拉菜单。页面加载中的第一个加载国家。然后,当一个国家被选中时,我会对webmethod进行ajax调用。我为属于该国家的团队获取数据。数据在我转换成JSON的数据集中,然后返回。在成功之后,我需要添加哪些代码来将json数据绑定到下拉列表。下面是 是代码。如何将json数据绑定到使用jquery的asp.net dropdownlist?

$(document).ready(function() { 

     $('#ddlcountries').change(function() { 

      debugger; 

      var countryID = $('#ddlcountries').val(); 

      $.ajax({ 

       type: "POST", 
       url: "Default.aspx/FillTeamsWM", 
       data: '{"CountryID":' + countryID + '}', 
       contentType: "application/json; charset=utf-8", 
      dataType: "json", 
       success: function(jsonObj) { 


       /* WHAT CODE DO I ADD HERE TO BIND THE JSON DATA 
       TO ASP.NET DROP DOWN LIST. I DID SOME GOOGLING 
       BUT COULD NOT GET PROPER ANSWER */ 


       }, 
       error: function() { 
        alert('error'); 
       } 

      }); 

     }); 


    }); 
+0

可能重复[如何使用jQuery将选项添加到DropDownList?](http://stackoverflow.com/questions/317095/how-do-i-add-options-to-a-dropdownlist -using-jquery) – 2012-02-05 17:40:40

+0

不要忘记,如果你想读取客户端修改的dropdow n列表(C#或VB),你需要使用Request.Form [“Control-ID”],因为你的第二个下拉列表中的数据是加载客户端(javascript)的。 – Zachary 2012-02-06 18:07:27

回答

0

根据你传递给客户端的内容,我假定它是一个List<string>。您可以根据您传递给客户端的内容来相应地调整代码,因为您没有告诉我们传回的内容。

所以,如果是这样的话做这样的事情:

// first remove the current options if any 
$('#ddlTeams').find('option').remove(); 

// next iterate thru your object adding each option to the drop down\  
$(jsonObj).each(function(index, item){ 
    $('#ddlTeams').append($('<option></option>').val(item).html(item)); 
}); 

再假设,如果您的列表具有包含teamid和`teamname11对象

// first remove the current options if any 
$('#ddlTeams').find('option').remove(); 

// next iterate thru your object adding each option to the drop down\  
$(jsonObj).each(function(index, item){ 
    $('#ddlTeams').append($('<option></option>').val(item.teamid).html(item.teamname)); 
}); 
+0

嗨Gabe,我尝试了代码,但它的工作!它是一个asp.net下拉控件,如果你把它弄糊涂成为