SIGN UP MEMBER LOGIN:    
ARTICLE

Persisting info into session using JavaScript

Posted by Manas Moharana Articles | Internet & Web May 24, 2010
In this article we will see how to persist info into session using JavaScript.
Reader Level:

I was working on a senario  where the responsibility was to impliment Product Comparison functionality.There was a requirement where I want to persisting info (product Id from different category page) across multiple pages using javascript. Then use those product ids in Product Comparison page.Each Product Category page shows  muliple products,  with a check box associated with each product, which  allow user  to select products to compare. As per requirement user can select products from diferent category and when click compare product button ,then all selected products from diferent page must be go to compare Product page.So I need to persist Product id in session.

1) To impliment this functionality I have used one Hidden input control to get data from cookie on load event.  

<input type="hidden" id="HiddenVar" runat="server" enableviewstate="true" />

2) To Collect  all selected  product Id, I have written  a javascript function and call it on onClick event of CheckBox.

checkbox.Attributes.Add("onClick", "updateProductIdInArray(this)");

Here I have used a global variable as  array to update selected Product ids .As a result whenever a uer check or uncheck the check box control, the array object will be updated  ( add or remove product id from array object) .Then update the value of hidden control by getting all ids from array object (you can write a separate function to get all product id from array  and make a text separated by comma ) .

3) Write a function to save the info in a Session and call the function when user click on  button or link to go to different page.The idea is before go to the specified page the javascript function will save the data from Hidden control value into a Session.

Control.Attribute.Add("onclick", "javascript:SaveSelectedProductId(););

Here I am using XmlHttprequest object to send a asyncronyous request to server by passing a Temp.aspx page url  .The url must have  a querystring and the value will be the data you want to save in session.The  main idea behind this to save the value in session when the requested page will render.e.x("/Pages/Temp.aspx?hiddenValue=" + dataTosave").

//Save Product Ids in Session
      function SaveSelectedProductId() {
        var MyHiddenControl = document.getElementById('<%= myHiddenVar.ClientID %>');
        var dataTosave = MyHiddenControl.value;
        var finalUrl = "/Pages/Temp.aspx?hiddenValue=" + dataTosave;
        var xmlhttp = false;
        try
        {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); /* for IE < 5 */
        }
        catch (e)
        {
           try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (E)
                { xmlhttp = false; }
                try { xmlhttp= new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
                catch (e) { }
                try { xmlhttp= new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
                catch (e) { }
        }  /* mozilla & opera */
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
         { xmlhttp = new XMLHttpRequest(); }
         
//initialize the XmlHttpRequest object
         xmlhttp.open("GET", finalUrl, true);
         //Send asyncronyous request to server
         xmlhttp.send(null); /* are sending null because we dont have any data to post */
    }

To store the value into session you need to write custom code by override the  OnPreRender method of Temp.aspx page.

protected override void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    string vlue=string.Empty;
    if (System.Web.HttpContext.Current.Request.QueryString["hiddenValue"] != null)
        vlue = System.Web.HttpContext.Current.Request.QueryString["hiddenValue"].ToString();
    Session["PrdIdsToComp"] = vlue;
}

4) Now the time to read the values from session and use, where you want to use the session value.

//Read value from session
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    if(Session["PrdIdsToComp"]!=null)
        // myHiddenVar is my Hidden value
        if (myHiddenVar != null)
            myHiddenVar.Value = Session["PrdIdsToComp"].ToString();
}
   
Issue: Some times issue with FirFox when  each request  create a  session with different Id.

Please let me know if some one resolve this issue.

Login to add your contents and source code to this article
share this article :
post comment
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Team Foundation Server Hosting
Become a Sponsor