2011-05-24 70 views
0

僅當用戶單擊第一次單擊DropDownList時,是否可以在asp.NET中加載下拉列表?使用jQuery加載下拉列表

我會盡力解釋它。我有一個帶有一個項目的DropDownList的aspx頁面。

ListItem listlt = new ListItem("UNDEFINED", "-1"); 
ddl.Items.Insert(0, listlt); 

我想在用戶點擊DropDownList時加載DropDownList中的所有數據。這是因爲下拉列表中包含大量數據,頁面負載非常緩慢。

有什麼想法? THX提前

回答

2

可以使用PageMethods代替。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.Services; 
public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 


    } 

    [WebMethod] 
    public static Dictionary<string, string> getItems() 
    { 
     return new Dictionary<string, string>(){ 
      {"1","Item1"} ,{"2","Item2"}}; 
    } 
} 

ASPX

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head> 
    <title>jQuery to call page methods in ASP.NET</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script> 
</head> 
<body> 
    <form id="Form1" runat="server"> 
    <asp:ScriptManager EnablePageMethods="true" ID="ScriptManager1" runat="server"> 
    </asp:ScriptManager> 

    <script type="text/javascript"> 
     $(document).ready(function() { 
      $('select#<%= DropDownList1.ClientID %>').click(function() { 

       if (this.options.length <= 0) { 
        PageMethods.getItems(function(res) { 
         //alert('e'); 
         for (r in res) { 
          //$(this).append($('<option value="'+ r+'">' + res[r] + '</option>')); 
          //$(this).append($('<option></option>')); 
          $('select#<%= DropDownList1.ClientID %>').append($('<option></option>').val(r).html(res[r])); 
         } 
        }); 
       } 
      }); 
     }); 
    </script> 
    <asp:DropDownList ID="DropDownList1" runat="server" /> 
    </form> 
</body> 
</html> 
0

使用jQuery load

$("select#theDropdownID").click(function(){ 
    $(this).load("thedropdownItems.html"); 
}); 

而且在thedropdownItems.html

<option value='foo'>foo</option> 
<option value='bar'>bar</option> 
....