最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Oct 21, 2011 at 7:35 Sai Kalyan Kumar Akshinthala 11.8k8 gold badges44 silver badges68 bronze badges asked Oct 21, 2011 at 7:33 NaningNaning 7342 gold badges8 silver badges18 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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"}; 

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

发布评论

评论列表(0)

  1. 暂无评论