Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to pass an object from c# code behind to javascript?

Tags:

javascript

c#

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?

like image 957
Naning Avatar asked Oct 21 '11 07:10

Naning


2 Answers

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"}; 
like image 190
Variant Avatar answered Oct 21 '22 15:10

Variant


Use JSON serialization to convert a .NET object into JS which can be deserialized into an object (or, exec'd into an object).

like image 34
Steve Avatar answered Oct 21 '22 14:10

Steve