13

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?

2 Answers 2

17

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"}; 
Sign up to request clarification or add additional context in comments.

1 Comment

Argument for using var on the oSerializer instantiation but good answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.