I am getting data back from my C# WebMethod. I’m not sure how to bind the Key and Value from my WebMethod to my dropdown:
<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;
}
Data
This is being passed to WebMethod
{
"state": "AL",
"city": "Auburn"
}
When debugging my WebMethod, I hover over ‘rest’ and it shows the Key and Value.
Don’t use a dictionary as this doesn’t serialize as a collection. Use a list:
And then:
also make sure to properly encode your values before sending them. I would recommend you using the JSON.stringify method because if the city has a quote in its name your request will break:
The JSON.stringify method is built into modern browsers but if you need to support legacy browsers you could include the json2.js script to your page.