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.
-
what r u trying to accomplish?Arief– Arief2011-09-26 13:06:47 +00:00Commented Sep 26, 2011 at 13:06
3 Answers
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
Comments
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.