.net 如何访问会话变量并在 javascript 中设置它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15519454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:10:27  来源:igfitidea点击:

How to access Session variables and set them in javascript?

javascript.netsession

提问by Mehmet Ince

In code-behind I set Sessionwith some data.

在代码隐藏中,我设置Session了一些数据。

Session["usedData"] = "sample data";

And the question is how can I get the Session value(in my example; "sample data") in javascript and set Session["usedData"]with a new value?

问题是如何在 javascript 中获取 Session 值(在我的示例中;“示例数据”)并设置Session["usedData"]一个新值?

采纳答案by SHEKHAR SHETE

Accessing & Assigning the Session Variable using Javascript:

使用 Javascript 访问和分配会话变量:

Assigning the ASP.NET Session Variable using Javascript:

使用 Javascript 分配 ASP.NET 会话变量:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

使用 Javascript 访问 ASP.NET Session 变量:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

回答by Darren

You can't access Sessiondirectly in JavaScript.

您不能Session直接在 JavaScript 中访问。

You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById

您可以创建一个隐藏字段并将其传递到您的页面,然后使用 JavaScript 通过以下方式检索对象 document.getElementById

回答by Ganesh

Javascript can not directly set session values. For setting session values from javascript I do ajax call as follows.

Javascript 不能直接设置会话值。为了从 javascript 设置会话值,我按如下方式执行 ajax 调用。

Check Online

在线查询

At ASPx file or html,

在 ASPx 文件或 html 中,

 <script type="text/javascript">
 $(function(){
   //Getting values from session and saving in javascript variable.
   // But this will be executed only at document.ready.
   var firstName = '<%= Session["FirstName"] ?? "" %>';
   var lastName = '<%= Session["LastName"] ?? "" %>';

   $("#FirstName").val(firstName);
   $("#LastName").val(lastName);

   $('Button').click(function(){
     //Posting values to save in session
     $.post(document.URL+'?mode=ajax', 
     {'FirstName':$("#FirstName").val(),
     'LastName':$("#LastName").val()
     } );
   });

 });

At Server side,

在服务器端,

protected void Page_Load(object sender, EventArgs e)
 {
      if(Request.QueryString["mode"] != null && Request.QueryString["mode"] == "ajax")
      {
        //Saving the variables in session. Variables are posted by ajax.
        Session["FirstName"] = Request.Form["FirstName"] ?? "";
        Session["LastName"] = Request.Form["LastName"] ?? "";
      }
 }

For getting session values, as said by Shekhar and Rajeev

获取会话值,如 Shekhar 和 Rajeev 所说

var firstName = '<%= Session["FirstName"] ?? "" %>';

Hope this helps.

希望这可以帮助。

回答by Rajeev Kumar

Try This

尝试这个

var sessionValue = '<%=Session["usedData"]%>'

回答by Quentin

Assuming you mean "client side JavaScript" - then you can't, at least not directly.

假设你的意思是“客户端 JavaScript”——那么你不能,至少不能直接。

The session data is stored on the server, so client side code can't see it without communicating with the server.

会话数据存储在服务器上,因此客户端代码在不与服务器通信的情况下无法看到它。

To access it you must make an HTTP request and have a server side program modify / read & return the data.

要访问它,您必须发出 HTTP 请求并让服务器端程序修改/读取并返回数据。

回答by btevfik

Assign value to a hidden field in the code-behind file. Access this value in your javascript like a normal HTML control.

为代码隐藏文件中的隐藏字段赋值。像普通的 HTML 控件一样在您的 javascript 中访问此值。

回答by Mohaimin Moin

You can't set session side session variables from Javascript. If you want to do this you need to create an AJAXPOSTto update this on the serverthough if the selection of a car is a major event it might just be easier to POSTthis.

您不能从Javascript. 如果要做到这一点,你需要创建一个AJAXPOST到上更新该服务器但如果汽车的选择是一个重大的事件很可能就是更容易POST这一点。

回答by Chandan Rajbhar

If you want read Session value in javascript.This code help for you.

如果您想在 javascript 中读取 Session 值。此代码对您有帮助。

<script type='text/javascript'> var userID='@Session["userID"]'; </script>

<script type='text/javascript'> var userID='@Session["userID"]'; </script>

回答by Behnam

first create a method in code behind to set session:

首先在后面的代码中创建一个方法来设置会话:

 [System.Web.Services.WebMethod]
 public static void SetSession(int id)
 {
     Page objp = new Page();
     objp.Session["IdBalanceSheet"] = id;
 }

then call it from client side:

然后从客户端调用它:

function ChangeSession(values) {
     PageMethods.SetSession(values);
     }

you should set EnablePageMethods to true:

您应该将 EnablePageMethods 设置为 true:

<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>

回答by code-it

Here is what worked for me. Javascript has this.

这对我有用。Javascript 有这个。

<script type="text/javascript">
var deptname = '';
</script>

C# Code behind has this - it could be put on the master page so it reset var on ever page change.

后面的 C# 代码有这个 - 它可以放在母版页上,以便在每次页面更改时重置 var。

        String csname1 = "LoadScript";
        Type cstype = p.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = p.ClientScript;

        // Check to see if the startup script is already registered.
        if (!cs.IsStartupScriptRegistered(cstype, csname1))
        {
            String cstext1 = funct;
            cs.RegisterStartupScript(cstype, csname1, "deptname = 'accounting'", true);
        }
        else
        {
            String cstext = funct;
            cs.RegisterClientScriptBlock(cstype, csname1, "deptname ='accounting'",true);
        }

Add this code to a button click to confirm deptname changed.

将此代码添加到按钮单击以确认部门名称已更改。

alert(deptname);