有什么方法可以将对象从 c# 代码后面传递给 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7846333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Any way to pass an object from c# code behind to javascript?
提问by Naning
I want to pass an object from my c# code behind to my javascript. I know that I can use
我想将一个对象从我的 c# 代码后面传递给我的 javascript。我知道我可以使用
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?
有没有办法做到这一点?
回答by Variant
You can serialize it to JSON using the JavaScriptSerializer
.
您可以使用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:
然后你可以在你的 aspx 代码中使用:
var myVar = <%# sJSON %>;
Which will output something like:
这将输出如下内容:
var myVar = {"Name":"John","Age":"30","ID":"111"};
回答by Steve
Use JSON serialization to convert a .NET object into JS which can be deserialized into an object (or, exec'd into an object).
使用 JSON 序列化将 .NET 对象转换为可以反序列化为对象(或执行为对象)的 JS。