2014-03-24 33 views
0

我有級聯下拉菜單。在選擇一個下拉列表時,另一個下拉列表使用ajax綁定。這完全工作,但我希望第二個下拉列表還應該包含默認文本和值(如'選擇我')。我如何添加這個默認值。這是我的代碼。在jquery ajax中添加默認值下拉電話

function BindCities(drpstate) { 
     var stateid = $(drpstate).val(); 
     $.ajax({ 
      url: '/Register.aspx/BindCities', 
      type: "POST", 
      async: false, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      data: '{"id":"' + stateid + '"}', 
      success: function (result) { 
       var drpcity = $('.drpcity'); 
       drpcity.empty(); 
       $.each(result.d, function() { 
        drpcity.append(
         $('<option/>', { 
          value: this.id, 
          text: this.name 

         }) 
        ); 
       }); 

      }, 
      error: function (xhr, status) { 
       alert(status + " - " + xhr.responseText); 
      } 
     }); 
    } 

HTML:

<asp:DropDownList runat="server" CssClass="drpstate" onchange="BindCities(this)" ID="drpdwnState"> 
          <asp:ListItem Text="Select State" Value="0"></asp:ListItem> 
         </asp:DropDownList> 

<asp:DropDownList runat="server" CssClass="drpcity" ID="drpdwnCity"> 
          <asp:ListItem Text="Select City" Value="0"></asp:ListItem> 
         </asp:DropDownList> 

服務器端代碼:

[WebMethod] 
    public static List<CountryState> BindCities(int id) 
    { 
     EkbnManager em = new EkbnManager(); 
     List<City> cities = em.GetCityByStateId(id); 

     List<CountryState> countrystate = new List<CountryState>(); 
     foreach (var item in cities) 
     { 
      CountryState cnt = new CountryState(); 
      cnt.name = item.Name; 
      cnt.id = item.Id; 
      countrystate.Add(cnt); 
     } 

     return countrystate; 
    } 

回答

1

在成功函數這樣做:

success: function (result) { 
        var drpcity = $('.drpcity'); 
        drpcity.empty(); 
        drpcity.append(
          $('<option/>', { 
           value: -1, 
           text: please select one 

          }) 
        $.each(result.d, function() { 
         drpcity.append(
          $('<option/>', { 
           value: this.id, 
           text: this.name 

          }) 
         ); 
        }); 
+0

感謝名單..其WO rking – Manu

+0

我還有一個問題。正如我使用ajax綁定下拉菜單。每當我選擇一個特定的值,我總是在服務器端獲得選定的值爲0?我如何訪問ajax綁定的下拉式服務器端的選定值? – Manu

+0

我需要使用隱藏字段嗎? – Manu

-1
$.ajax({ 
      type: "POST", 
      contentType: "application/json; charset=utf-8", 
      url: "WebService.asmx/GetMethod", 
      data: "", 
      dataType: "json", 
      success: function (data) { 
       $("#drpName").empty(); 
       $("<option value='-1'>(Select item)</option>").appendTo("#drpName"); 
       $.each(data.d, function (key, value) { 
        $("#drpName").append($("<option></option>").val(value.ID).html(value.Title)); 
       }); 
      }, 
      error: function (result) { 
       alert("Could not get!"); 
      } 
     });