Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
In my c# code, I store an array in session. Below is the c# code

C#
protected void loadDuties()
       {
           MyClass M = new MyClass();
           string[] duties = null;
           duties = M.get_Duties();
           Session["duties"]= duties;
           //return duties;
       }


And on my master page, I want to retrieve this array.

XML
<script>
    function load() {
         var duties = new Array();
        duties = '<%=Session["duties"].ToString()%>';
        alert(duties.toString());
        for (i = 0; i < duties.length; i++)
            {
            document.getElementById(duties[i]).style.display = "block";
            }
                   }
                   window.onload = load;
   </script>


But the alert prints System.String[]
Please help
Posted
Comments
F-ES Sitecore 31-Jul-15 6:10am    
Your .net code isn't running inside the browser, your js can't access server objects. The .net code generates static html which is sent to the browser to use. When you write Session["duties"].ToString then you get the type name written to the html which is why you're seeing System.String[] in the source.

Render the array as json rather than ToString and you can then use the duties variable like a json object as the source will then contain your array as json mark-up.

var duties = <%= yourArrayAsJSON %>

Google "asp.net serialise object to json" and you'll find examples.

First Serialize then use ....

XML
    var dataArray = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Session["duties"])%>

    alert(dataArray[1]);
</script>
 
Share this answer
 
v3
Comments
Member 10820603 31-Jul-15 19:26pm    
Thanks so much. It worked perfectly.
Hi,

First of all reaching session objects from hidden inputs is a more prefable way. But for this purpose you have to convert your array into a JSON object. You can do it with Javascript Serializer[^]

To do it place a hidden object into your page:

<input runat="server" type="hidden" name="myhidden" id="myhidden" />


Afterwards set your session value into it as well from the codebehind,

myhidden.Value = "YOUR DUTIES";


Then it's easy to reach this hidden input from javascript.

alert(document.form1.myhidden.value)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900