我从C#WebMethod获取数据。我不确定如何将Key和Value从我的WebMethod绑定到我的下拉列表中:
<select name="rest" id="rest" maxlength="50" style="width: 200px;"></select>
C#
[WebMethod]
public static Dictionary<string, string> LoadRestByCityState(string city, string state)
{
DataSet ds = new DataSet();
Database db = DatabaseFactory.CreateDatabase(ConfigManager.AppSettings["ConnectionString.Data"]);
DbCommand dbCommand = db.GetStoredProcCommand("sel_RestByCityState_p");
db.AddInParameter(dbCommand, "@pListCity", DbType.String, city);
db.AddInParameter(dbCommand, "@pListState", DbType.String, state);
ds = db.ExecuteDataSet(dbCommand);
Dictionary<string, string> rest = new Dictionary<string,string>();
foreach (DataRow row in ds.Tables[0].Rows)
{
rest.Add(row[0].ToString(), row[1].ToString());
}
return rest;
}
的jQuery
function LoadRest() {
__state = $("#State :selected").val();
__state = '"' + __state + '"'
__city = $("#City :selected").val();
__city = '"' + __city + '"'
$.ajax({
type: "POST",
url: "Default.aspx/LoadRestByCityState",
data: '{"city":' + __city + ',"state":'+ __state +'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success:
function (data) {
$.each(data[0], function(key....not sure about this stuff
alert('parks loaded');
},
fail: function () {
alert("Error.");
}
});
return false;
}
数据 这将被传递给WebMethod
{
"state": "AL",
"city": "Auburn"
}
在调试我的WebMethod时,我将鼠标悬停在'rest'上,它会显示Key和Value。
答案 0 :(得分:2)
不要使用字典,因为这不会作为集合序列化。使用清单:
public static List<KeyValuePair<string, string>> LoadRestByCityState(string city, string state)
{
...
}
然后:
success: function (data) {
var rest = $('#rest');
rest.empty();
$.each(data.d, function(index, item) {
rest.append(
$('<option/>', {
value: item.Key,
text: item.Value
})
);
});
}
还要确保在发送之前正确编码您的值。我建议您使用JSON.stringify方法,因为如果城市名称中有引号,您的请求将会中断:
data: JSON.stringify({city: __city, state: __state }),
JSON.stringify方法内置于现代浏览器中,但如果您需要支持旧版浏览器,则可以在页面中加入json2.js脚本。
答案 1 :(得分:1)
试试这个
success : function(data){
$.each(data, function(index, elem){
$.each(elem, function(key,value){
$('select#rest').append('<option value="'+key+'">"'+value+'"</option>');
});
});
}
更新其他解决方案
success : function(data){
$.each(data, function(index, elem){
for(var key in elem){
$('select#rest').append('<option value="'+key+'">"'+elem[key]+'"</option>');
}
});
}