在我的asp.net網頁中,我使用JavaScriptSerializer類的幫助準備了JSon字符串。 我已經吐了JSON字符串中的HTML標記用的RegisterStartupScript方法的幫助下,它看起來像這樣,將json變量數據綁定到jquery的下拉列表中
C#.NET代碼編寫的JSON字符串,
System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, string>> glAccts = new List<Dictionary<string, string>>();
Dictionary<string, string> row;
foreach (DataRow dr in _dtProfitCenterRawData.Rows)
{
row = new Dictionary<string, string>();
row.Add(dr[0].ToString(), dr[1].ToString());
glAccts.Add(row);
}
string jsonObj = jsSerializer.Serialize(glAccts);
string script = "var glList = " + jsonObj + ";";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(Page.GetType(), "JSONObj", script, true);
上glList變量客戶端html看起來像這樣,
var glList = [
{ "1110005": "1110005 - X1" },
{ "1110008": "1110008 - X2" },
{ "1110011": "1110011 - X3" },
{ "1110020": "1110020 - X4" }
];
我想將此json字符串綁定到dropdownlist控件。請建議如何執行該操作?我試圖執行以下操作來查看對象內部的數據,但它不會給我真正的值。它在alert方法中給出[object]。
請建議修復的問題..
$.each(glList, function (val, text) {
//$('#mySelect').append(new Option(text, val));
alert(text); alert(val);
});
可能的重複[什麼是從jQuery選擇數組中添加選項的最佳方式?](http://stackoverflow.com/questions/170986/what-is-the-best-way -I-add-options-a-select-from-an-an-array-with-jquery) – Jono
Yeh,我試過但它不適用於我..我是否需要從變量中刪除[,]括號glList ?? – Karan
他們的JSON數據和你的唯一區別是他們有{「key1」:「value」,「key2」:「value」,「key3」:「value」}的對象,而你有一個[{ 「key」:「value」},{「key」:「value」},{「key」:「value」}] – Jono