简体   繁体   中英

How do you set a session variable in JavaScript?

Can this be done with a PageMethods call? I need to save some variables in a control so that they can be used by a control on another page at a later time. Is there a way to do this via JavaScript?

听起来您需要CookielocalStorage或sessionStorage

您可以使用JS来更改隐藏字段中的值,并在回发中捕获它们,就我个人而言,如果仅在当前会话的生命周期中需要该值,我个人认为这比使用cookie更可取。

Session variables cannot be set using Javascript directly But you can use the following code to set session variables in aspx page

<%Session["SESSION VARIABLE NAME"] ="SOME STRING"; %>

You can check the same variable using an alert in javascript

 alert('<%=Session["SESSION VARIABLE NAME"] %>');

Yes session variable can be set using Pagemethods using the below way

declare the below code in aspx.cs page

  [WebMethod]
        public static void functionname(string st)
        {
            Home h = new Home();
            System.Web.HttpContext.Current.Session["SessionUserName"] = st;
            h.strUserName = (string)System.Web.HttpContext.Current.Session["SessionUserName"];
        }

and call the function using pagemethod in aspx

 PageMethods.functionname("HELLO");

this will set the session variable to HELLO

You can also make an ajax call to the webmethod if you dont want to use pagemethods.function!!

It's a very bad idea to do this with PageMethods.

You can add a generic handler (*.ashx) and then do a XMLhttpRequest to this URL, passing it parameters.

Note that the ashx handler needs to inherit from IRequiresSessionState, in order to access a session.

You can also get a session value that way.

Like this:

using System.Web;
using System.Web.SessionState;

public class Handler : IHttpHandler , IRequiresSessionState
{
   public void ProcessRequest (HttpContext context) 
   {
      context.Response.ContentType = "text/plain";
      context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

      string item = context.Request.QueryString["item"] ?? "";
      string update = context.Request.QueryString["update"] ?? "";

      switch (item)
      {
         case "A":

            if (!string.IsNullOrEmpty(update))
               context.Session["A"] = update

            object a = context.Session["A"];   
            context.Response.Write(a != null ? (string) a : "none");

            break;

         case "B":

            if (!string.IsNullOrEmpty(update))
               context.Session["B"] = update

            object b = context.Session["B"];
            context.Response.Write(b != null ? (string) b : "none");

            break;
      }
   }

   public bool IsReusable 
   {
      get { return false; }
   }
} 

See my post here for XMLhttpRequest: Why does this JavaScript code ignore the timeout?

You might want to add a parameter no_cache=TIME_IN_MILLISECONDS, in order to beat browser caching.

I like to do it the following way:

javascript:

function SendData(data) {
    var postbackarg = "@@@@@" + data;
    __doPostBack("txtTest", postbackarg);
}

VB In Page_Load event:

If Me.IsPostBack Then
    Dim controlName As String = Request.Params.Get("__EVENTTARGET")
    Dim args As String = Request.Params.Get("__EVENTARGUMENT")
    ProcessUserInterfaceData(controlName, args)
    If (controlName = "txtTest" AndAlso args.IndexOf("@@@@@") = 0) Then
        args = args.Substring(5, args.Length - 5)
        'args now = data from the UI
    End If
End If

This started from an example I found somewhere else. I cannot find it.. The only purpose for the 5 '@' is to identify the postback as coming from SendData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM