Oussema Oz
Oussema Oz

Reputation: 21

Define session variable in c# get it from javascript

I'm saving string that represents the URL in a session variable from my code behind like this:

        String mois = Request.QueryString["mois"].ToString();
        String m = mois;


        String moisnom = Request.QueryString["moisnom"].ToString();
        String annee = Request.QueryString["annee"].ToString();
        String dt = Request.QueryString["date"].ToString();
        String user = Request.QueryString["user"].ToString();
        String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
        Session["togo"] = where; 

And then I try to get it like this in JavaScript like this:

    var togo = '<%=Session["togo"]%>';
    //  i also tried this var togo ='@Session["togo"]'; 
    var newPage = togo; // this should contain a string with the url to go to 

But when I use it it uses it as a string here is what my URL looks like:

http://localhost:50311/<%=Session["togo"]%>
 or
http://localhost:50311/@Session["togo"]

How else can I access the session variable or what am I doing wrong please?

 EDIT: 
like you suggested i already tried using the hidden field like this 

     yes  i tried that but then i had this problem here is the definition of the hidden field  

             <input type="hidden" value="aa" id="myHiddenVar" runat="server"/>

then i tried giving it the value i need on click

            String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
        myHiddenVar.Value= where; 

and this is how i tried getting it from the js file

       var togo = $('#myHiddenVar').val();
       var newPage = togo;

but it takes the default value meaning "aa" as in value="aa" i gues cause the script is executed before the assignment of the variable any way how to reverse that order ?

Upvotes: 0

Views: 176

Answers (3)

Nodiink
Nodiink

Reputation: 360

Write Session element in a asp:HiddenField and then read from it with your js code.

Upvotes: 0

Sameer
Sameer

Reputation: 705

first of all session resides on server!!!!!!

If it is in different js file than you cant access it <%xyz%> i.e scriplet tags only work on aspx page...

so there is no way to access the session variable on client side..

instead assign your sessio9n value to a hidden variable and then access it using javascript

Upvotes: 1

Devesh Pandey
Devesh Pandey

Reputation: 48

After Session["togo"] = where; save this Session["togo"] in hidden variable

hiddenVariable= Session["togo"];

Now in JS access that hiddenvariable: suppose ID of hiddenvariable is "hdnxyz"

var togo = $('#hdnxyz').val();

var newPage = togo;

Upvotes: 1

Related Questions