我正在尝试通过将数据传递给 WCF 来绑定 JQuery 中的下拉列表。
jQuery代码是:
function PopulateCity()
{
var StateID = { 'stateId': $("[id$=ddlState]").val() };
var jsondata = JSON.stringify(StateID);
$('[id$=ddlCity]').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax({
type: "POST",
url: 'http://localhost:49583/Service1.svc/PopulateCities',
data: jsondata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
BindCity(data,'ddlCity');
},
failure: function (response) {
alert(response);
}
});
}
function BindCity(list, control) {
$.each(list, function (value, text) {
$("select[id$=" + control + "]").append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
WCF 代码是:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
List<CityDetails> PopulateCities(int stateId);
实现的接口是:
List<CityDetails> IService1.PopulateCities(int stateId) {
List<CityDetails> arrCity = new List<CityDetails>();
String strConnString = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
//String strQuery = "select ID, CityName from Cities where CountryID=@CountryID";
String strSP = "Car_GetSubMasterDetails";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@MasterID", stateId);
cmd.Parameters.AddWithValue("@Key", "City");
cmd.Parameters.AddWithValue("@Culture", "en-US");
cmd.CommandText = strSP;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
arrCity.Add(new CityDetails() { Value = sdr["ID"].ToString(), Text = sdr["CityName_en_US"].ToString() });
// list.Add(new ListItem(
//sdr["CityName_en_US"].ToString(),
//sdr["ID"].ToString()
// ));
}
con.Close();
return arrCity;
}
}
}
我不明白我错在哪里。它既没有绑定下拉列表也没有显示任何错误。请帮助..提前致谢。