user3116539
user3116539

Reputation: 49

How to use asp.net sessions in javascript?

I have a form in Asp.Net with 3 pages by going with a next button to the next page. What I've done so far in C# is I created sessions like this:

Session["FirstName"] = txtFirst.Text;
Session["LastName"] = txtLast.Text;

Than what I did is on that Next button I called a javascript function where I tried to access these sessions like this:

<script type="text/javascript">
    var fn = '<%=Session["FirstName"]%>';
    var ln = '<%=Session["LastName"]%>';
</script> 

But it's not working, when I am debugging it gets exactly what we entered inside quotes: http://prntscr.com/ag3wdo

Upvotes: 0

Views: 638

Answers (3)

Hans Kesting
Hans Kesting

Reputation: 39284

That syntax: <%=Session["FirstName"]%> is a special asp.net syntax. It needs to be processed on the server, where it gets replaced with the value of that session value. Only then does this get sent to the browser.

Some important notes:

  • the browser doesn't understand that <%= ... %> syntax
  • the server needs to process it, so it must be in a file that is processed, like an .aspx or .ascx
  • a javascript file (.js) is sent as-is, without extra processing, so this syntax doesn't work here.

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156978

Most likely those tags are in a .js file, not an aspx or ascx page. Those tags only work on those extensions. Javascript files are sent as-is.

You can do a few things:

  • Create a setup stub in your page, maybe from your master page, that sets the variables in javascript so you can use them later on.
  • Load the file from an ashx handler and replace the session tags by hand.
  • Load the entire Javascript file in your page. This isn't really a good idea when the file is big.

Upvotes: 0

Nikki9696
Nikki9696

Reputation: 6348

You need to either have that script directly in an aspx page (not a .js file), or you need to set the values of the variables from a script in the aspx page.

Alternatively, you could send the js files to be evaluated by the .NET engine (create a handler), but that's not a good thing to do, as a general rule because it would process ALL js files and add overhead where you don't need it.

Last resort, you can set the values in a hidden field to then be accessed by javascript later. See Accessing Asp.Net Session variables in JS

Upvotes: 0

Related Questions