Arraylist and webmethod
I have written a web method in ASP.net which it's output is an ArrayList of cities that is read from Sql server database. this webmethod is called using Jquery in clientside. but I don't know how to read each item of array list using jquery. for example every city and it's id equivalent. Below is my 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 stateid=@s";
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;
}
}
and this is my clientside code:
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"); }
})
}
If I use alert(data.d)
I will get [object][object][object][object],.....
You need to create an actual type and return an array of that type. So create a City class, mark it serializable, build a List<City>
in your loop, then return .ToArray(). The return type of your web method should be City[]
Instead of ArrayList
being returned, it would be better to return an array with two dimension.
I found a solution myself so I share it here, just be careful about Value
and Text
they're case sensitive
success: function(data) {
$.each(data.d, function() {
alert(this['Value'] + ':' + this['Text']);
})
}
精彩评论