0

I have a button with a js onClick function. When the button is clicked I'd like to save a value so after I go to a new page it can be read from the behind code. I'm familiar with the Session[] variable in behind code and the the SessionStorage in the client side, but not how to share between them.

I guess I'm aksing how can I save a variable from a js function to be read later in a page's behind code.

  <script "text/javascript">

           $('.toggle a').click(function () {
               var select = $(this);

                   if (select.hasClass("active")) {                      
                   var newValue = "Wow!"
                   //save newValue into test
                   alert('<%= Session["test"] %>');
                   window.location.assign("Contact.aspx");

               }else
                   select.parents('li').toggleClass('is-open');

           });

//BEHIND CODE Site.Master.cs

    `using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;


    namespace WebApplication6{


public partial class SiteMaster : MasterPage
{
    private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;

    protected void Page_Init(object sender, EventArgs e)
    {


    }


    protected void master_Page_PreLoad(object sender, EventArgs e)
    {

    }

    protected void Page_Load(object sender, EventArgs e)
    {

        //if (navTree.Nodes.Count != 0) return;
        TreeView navTree = new TreeView();
        Service1 myService = new Service1();

        //Use a gridview to store the table data before building the menu
        GridView sites = new GridView();

        sites.DataSource = myService.GetAllSites();
        sites.DataBind();




        //After the gridview is filled iterate through rows, adding new nodes
        //for each site and children for each rule
        foreach (GridViewRow siteRow in sites.Rows)
        {


            String siteName = siteRow.Cells[1].Text;

            TreeNode existingNode = isParent(siteName, navTree);
            if (existingNode == null)
            {
                TreeNode ParentNode = new TreeNode(siteRow.Cells[1].Text);
                ParentNode.SelectAction = TreeNodeSelectAction.Expand;
                ParentNode.Collapse();
                navTree.Nodes.Add(ParentNode);

                TreeNode ChildNode = new TreeNode(siteRow.Cells[2].Text);
                ChildNode.NavigateUrl = "http://gamespot.com";
                ParentNode.ChildNodes.Add(ChildNode);
            }
            else
            {
                TreeNode ChildNode = new TreeNode(siteRow.Cells[2].Text);
                ChildNode.NavigateUrl = "http://kotaku.com";
                existingNode.ChildNodes.Add(ChildNode);
            }

        }

        createMenu(navTree);

    }




    }

    [WebMethod(EnableSession = true)]
    public static void SetSessionValue(string sessionValue)
    {
        HttpContext.Current.Session["test"] = sessionValue;

    }




}

}

1
  • 1
    Where is your code? What have you tried? Commented Aug 9, 2013 at 1:22

1 Answer 1

3

Well without seeing what you have tried, I recommend using an ASP.NET AJAX Page Method to use as a conduit between your client-side session value and storing it in ASP.NET Session cache, like this:

Client-side:

$.ajax({
    type: "POST",
    url: "YourPage.aspx/StoreSessionValue",
    data: {"sessionValue": "theSessionValue"},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert("Successfully save session value.");
    }
});

Server-side (YourPage.aspx):

[WebMethod(EnableSession = true)]
public static void StoreSessionValue(string sessionValue)
{
    HttpContext.Current.Session["TheSessionValue"] = sessionValue;
}

Now, in your normal ASP.NET page lifecycle you can access the Session value, like this:

protected void Page_Load(object sender, EventArgs e)
{
    if(Session["TheSessionValue"] != null)
    {
        string theSessionValue = Session["TheSessionValue"] as string;

        // Do something with or based upon the session value here
    }
}

UPDATE:

Change your JavaScript to this:

<script "text/javascript">
   $('.toggle a').click(function () {
       var select = $(this);

       if (select.hasClass("active")) {                      
           var newValue = "Wow!"
           //save newValue into test
           $.ajax({
               type: "POST",
               url: "YourPage.aspx/StoreSessionValue",
               data: {"sessionValue": "theSessionValue"},
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function(msg) {
                   alert("Successfully save session value.");
                   window.location.assign("Contact.aspx");
               }
           });
           //alert('<%= Session["test"] %>');

       }else
           select.parents('li').toggleClass('is-open');
   });

Note: Rename YourPage.aspx/StoreSessionValue to your page name and web method name.

Sign up to request clarification or add additional context in comments.

18 Comments

Looks interesting. I'll give it a try!
Oh, I found an issue I ran into before. The Session variable in the webMethod function gives the error: An object reference is required for the non-static field, method, or property 'System.Web.UI.UserControl.Session.get'
@WillTuttle - are you talking about the example code I posted or yours? If yours, then post your web method code.
I pasted yoru webmethod into my .cs file
Sorry trying to do too many things at once lately, I forgot the EnableSession = true part of the WebMethod decoration, updated answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.