2011-03-24 39 views
1

我在ASP.net中編寫了一個web方法,輸出的是從Sql server數據庫中讀取的城市ArrayList。 此webmethod在客戶端使用Jquery調用。 但我不知道如何使用jQuery讀取數組列表的每個項目。例如每個城市和它的id等值。 下面是我的WebMethod:Arraylist和webmethod

public ArrayList showcity(int s) 
    { 
      ArrayList list = new ArrayList(); 
      String strConnString = ConfigurationManager 
       .ConnectionStrings["ConnectionCS"].ConnectionString; 
      String strQuery = "select ID, City from tbl_city where [email protected]"; 
      using (SqlConnection con = new SqlConnection(strConnString)) 
      { 
       using (SqlCommand cmd = new SqlCommand()) 
       { 
        cmd.CommandType = CommandType.Text; 
        cmd.Parameters.AddWithValue("@s", s); 
        cmd.CommandText = strQuery; 
        cmd.Connection = con; 
        con.Open(); 
        SqlDataReader sdr = cmd.ExecuteReader(); 
        while (sdr.Read()) 
        { 
         list.Add(new ListItem(
         sdr["City"].ToString(), 
         sdr["ID"].ToString() 
         )); 
        } 
        con.Close(); 
        return list; 
       } 
      } 

,這是我的客戶方代碼:

function showcity() { 
     $.ajax(
    { url: "../AjaxServices/StateCity.asmx/showcity", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     type: "POST", 
     data: '{s: ' + $('#<%=DpState.ClientID%>').val() + '}', 
     success: function(data) { 
      ***// what should I write here to access every item separately*** 
      }, 
     error: function() { alert("Error"); } 
    }) 
} 

如果我使用alert(data.d)我會[對象] [對象] [對象] [對象] ... ..

回答

0

我找到了解決自己,所以我在這裏分享它,只是要小心ValueText他們是大小寫敏感的

success: function(data) { 
       $.each(data.d, function() { 
        alert(this['Value'] + ':' + this['Text']); 
       }) 
      } 
2

您需要創建一個實際類型並返回該類型的數組。因此,創建一個City類,將其標記爲可序列化,在循環中創建一個List<City>,然後返回.ToArray()。您的Web方法的返回類型應爲City []

+0

你不介意做一個例子嗎? – 2011-03-24 13:01:55

0

而不是返回ArrayList,最好是返回具有兩個維度的數組。