Friday, February 6, 2009

How To access session variable in javascript

<script language="JavaScript">

var MySessionvalue = <% = Session("key") %>;
...
</script>

No way possible without creating a PostBack or using AJAX. Here's an example using a PostBack:
aspx file:
<script type="text/javascript">
<!--
function setSessionVariable(valueToSetTo)
{
 __doPostBack('SetSessionVariable', valueToSetTo);
}
// -->
</script>
aspx.cs file:
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;
  }
 }
}


<script type="text/javascript" language="javascript">

var sessionValue = '<%= Session["SesValue"] %>';
alert(sessionValue);

</script>
 Put This Script In Your Page Inline

0 Ads:

Post a Comment