Reputation: 3338
In my asp.net web page, I have prepared the JSon string with the help of JavaScriptSerializer class. And i have spit the Json string in to the HTML markup with the help of RegisterStartupScript method and it looks like this,
C#.net code to prepare the json string,
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);
The glList variable on the client html looks like this,
var glList = [
{ "1110005": "1110005 - X1" },
{ "1110008": "1110008 - X2" },
{ "1110011": "1110011 - X3" },
{ "1110020": "1110020 - X4" }
];
I want to bind this json string to dropdownlist control. Please suggest how to perform that? I tried to perform the following action to view the data inside the object, but it does not give me the real values. It gives [object] in the alert methods.
Please suggest the fix to the problem..
$.each(glList, function (val, text) {
//$('#mySelect').append(new Option(text, val));
alert(text); alert(val);
});
Upvotes: 0
Views: 1503
Reputation: 950
Try this here. If you itereate through glList
you get the objects but not their properties.
function jsonTest() {
$.each(glList, function(index, obj) {
($.each(obj, function (key, value) {
$('#mySelect').append(new Option(key, value));
}));
});
}
Upvotes: 2
Reputation: 16
try
var glList = [
{ 1110005: "1110005 - X1" },
{ 1110008: "1110008 - X2" },
{ 1110011: "1110011 - X3" },
{ 1110020: "1110020 - X4" }
];
Upvotes: 0
Reputation: 1726
Use JSON.Net instead JavaScriptSerializer
to serialize a Dictionnary.
Or you can try to cast to object before serialize
jsSerializer.Serialize((object)glAccts)
Upvotes: 0