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

后端 未结 2 948
醉梦人生
醉梦人生 2020-12-10 04:04

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 variab

相关标签:
2条回答
  • 2020-12-10 04:26

    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"}; 
    
    0 讨论(0)
  • 2020-12-10 04:38

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

    0 讨论(0)
提交回复
热议问题