Wednesday, June 13, 2012

How Set and Get ASP.NET session variables with JavaScript

Is there any possible method to directly set ASP.NET session variable with JavaScript? NO. You cannot directly set a session variable via JavaScript. But there is a work around.

In the early days of classic ASP, we achieved this by using a hidden frame and use a server post back behind the scene.

But with AJAX, we no longer need hidden frames. All you have to do is, create a new page which accepts the parameters you need to set and then call that page with necessary parameters.

JavaScript
var url = "AjaxCall.aspx?Userid= " + Userid; req = new ActiveXObject("Microsoft.XMLHTTP"); req.open("POST", url, true); req.send();

AjaxCall.aspx
private void Page_Load(object sender, System.EventArgs e)
{
if(Request.QueryString["Userid"] != null)
{
Session["Userid"] =Request.QueryString["Userid"].ToString();
}
}

You can access the Session variable in your HTML page.

userid = <%=Session["Userid"]%>
Then after render it will show you the session value at the page



userid = 000912


Hope This Help..
Please leave a comment below.

2 comments: