如何将值从表单分配给 Javascript 会话变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24056472/
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-10-28 02:05:14  来源:igfitidea点击:

How to assign values from form to Javascript session variables

javascripthtmlasp.netsession-variables

提问by MarsOne

I am trying to create Javascript Session variables that will read information from one form and pass these variables to another form.

我正在尝试创建 Javascript 会话变量,这些变量将从一个表单读取信息并将这些变量传递给另一个表单。

I can assign strings to these Session variables but i cannot assign values from Form elements to these variables

我可以将字符串分配给这些 Session 变量,但我不能将值从 Form 元素分配给这些变量

function SetUserName() 
{       
     <% var text1= "Charles";%>
     <%Session["UserName"] =text1;%>
     var session_value='<%=Session["UserName"]%>';
}
</script>

This is the Javascript on the first page which works and on a button click i call another page where i can display this Session Variable.

这是第一页上的 Javascript,在单击按钮时我会调用另一个页面,我可以在其中显示此会话变量。

function LoadUserName()
{
    var username = '<%= Session["UserName"] %>';
    alert(username);
}

This gets called on load of second page. How can i pass values from HTML elements to the Session Variable?

这在加载第二页时被调用。如何将值从 HTML 元素传递到会话变量?

For Example Say i have a Text Box

例如说我有一个文本框

 <asp:TextBox ID="Address_Box" runat="server"  TextMode="MultiLine"
             MaxLength="200" ></asp:TextBox>

How can I send the text from this box to the session variable?

如何将文本从此框中发送到会话变量?

回答by matt_lethargic

You would have to put this somewhere in your c# code.

您必须将其放在 c# 代码中的某个位置。

Session["UserName"] = Address_Box.Text;

For a more complete answer I'd have to see more of your code. For a better solution you'd have to explain what you're trying to achieve

要获得更完整的答案,我必须查看您的更多代码。为了更好的解决方案,您必须解释您要实现的目标

回答by Hans Ke?ing

Your code:

您的代码:

var session_value='<%=Session["UserName"]%>';

does not "access the ASP.Net session from javascript".

不会“从 javascript 访问 ASP.Net 会话”。

With this code you do generate (during the processing of the request) some text that will be sent to the browser. This text contains the string that results from the expression Session["UserName"].

使用此代码,您可以生成(在处理请求期间)一些将发送到浏览器的文本。此文本包含由表达式产生的字符串Session["UserName"]

Once this text arrives at the browser it is interpreted as javascript. This javascript has no knowledge of any session values or the fact that it was (partly) generated.

一旦此文本到达浏览器,它就会被解释为 javascript。这个 javascript 不知道任何会话值,也不知道它是(部分)生成的。

You need to find some way to send data from the browser back to the server (using postback or ajax, for instance) before it can be stored in Session.

您需要找到某种方法将数据从浏览器发送回服务器(例如使用回发或 ajax),然后才能将其存储在 Session 中。