Rauf
Rauf

Reputation: 12842

Access ASP.NET session variable from JavaScript

When the code var accNo = '<%=Session["hdnAccession"]%>'; will be executed ?. I change the session variable in the Page_LoadComplete event, but when I access it using var accNo = '<%=Session["hdnAccession"]%>';, it always return the value which I set FIRST. In Page_LoadComplete, I do like the following... Session["hdnAccession"] = GetNewAccession(), When I debugged, I saw that the Session["hdnAccession"] updated each time. But why it do not get updated in JavaScript ?. I am in a situation where I can not use HiddenField instead of Seession.

Upvotes: 2

Views: 25245

Answers (3)

Amit
Amit

Reputation: 1184

Your code block is getting its values when the page is rendered, and therefore any values set in Page_Load or Page_LoadCompleted should be seen properly in the client side.

If it isn't, there must be a different problem - try testing this by adding a temporary property to the page, initialize it in Page_Load and write it into the client side (i.e, var test = "<%=SomeProperty%>";).

If the problem occurs only after performing a postback (it is not very clear from your question), you will probably have to use hidden fields after all. There may be other ways to handle this, but I can't see a situation where you will be able to implement them and not be able to add hidden fields.

Upvotes: 0

Svarog
Svarog

Reputation: 2208

You must use some server-side control to do it(such as HiddenField or hidden span with runat="server").

<%=Session["hdnAccession"]%> will only evaluate the first time you enter the page, not during postbacks.

Upvotes: 1

Mack
Mack

Reputation: 823

You need to create a PostBack to access session variables from JS. Like so:

<script type="text/javascript">
<!--
function setSessionVariable(valueToSetTo)
{
 __doPostBack('SetSessionVariable', valueToSetTo);
}
// -->
</script>

private void Page_Load(object sender, System.EventArgs e)
{
 // Insure that the __doPostBack() JavaScript method is created...
 this.GetPostBackEventReference(this, string.Empty);

 if ( this.IsPostBack )
 {
  string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
  string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];

  if ( eventTarget == "SetSessionVariable" )
  {
   Session["someSessionKey"] = eventArgument;
  }
 }
}

See here: http://forums.asp.net/post/2230824.aspx

Upvotes: 2

Related Questions