Monday, May 20, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  93] [ 6]  / answers: 1 / hits: 18271  / 13 Years ago, fri, october 21, 2011, 12:00:00

I want to pass an object from my c# code behind to my javascript. I know that I can use



var myVar = '<%# myVar %>' 


to pass variables. However, that method seems to pass everything as a string. I want an object.



Is there any way to accomplish that?


More From » c#

 Answers
9

You can serialize it to JSON using the JavaScriptSerializer.



Something like:



System.Web.Script.Serialization.JavaScriptSerializer oSerializer = 
new System.Web.Script.Serialization.JavaScriptSerializer();

string sJSON = oSerializer.Serialize(myVar);


Then you in your aspx code you can use:



var myVar = <%# sJSON %>; 


Which will output something like:



var myVar = {Name:John,Age:30,ID:111}; 

[#89504] Wednesday, October 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dorothylorrainef

Total Points: 456
Total Questions: 102
Total Answers: 115

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;