C# 在 JS 中访问 Asp.Net Session 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14213809/
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
Accessing Asp.Net Session variables in JS
提问by Ksnrg
I'm not able to access the variable in my .js file
我无法访问 .js 文件中的变量
the code i have at the top of the page is:
我在页面顶部的代码是:
<script type="text/javascript">
privilage = '<%=Session["privilage"]%>';
</script>
then i want to access privilage in my .js file.
然后我想在我的 .js 文件中访问权限。
i just want to alert this at the moment. would i be able to do this?
我现在只想提醒一下。我能做到吗?
thanks
谢谢
采纳答案by Aarif Qureshi
You have to store session Value in HiddenField. After that You can Access the HiddneFieldValue in your JS
您必须将会话值存储在 HiddenField 中。之后你可以在你的 JS 中访问 HiddneFieldValue
<script type="text/javascript">
document.getElementById('hdnField').value = '<%=Session["privilage"]%>';
</script>
回答by Renjith JR
Just use:
只需使用:
var privilage = '<%=Session["privilage"]%>';
or try:
或尝试:
alert(privilage);
It will display your Session value
它将显示您的会话值
回答by Elyor
use
用
<script type="text/javascript">
var privilage = '<%=Session["privilage"]%>';
</script>
回答by m4f1050
I use it this way.
我是这样用的。
<asp:TextBox ID="txtValue" runat="server" CssClass="txtValue" style="display: none;" />
Then I use jQuery to access the value.
然后我使用 jQuery 访问该值。
<script>
var txtValue = $(".txtValue").val();
</script>
Or even on a control.
甚至在控件上。
<asp:LinkButton ID="lnkPrint" runat="server" CausesValidation="true"
CommandName="Print" CommandArgument='<%# Bind("PrintData") %>'
Text="<img src='/images/print_on.png' onmouseover='cursor: pointer;'
class='PrintButton' />" ToolTip="Print" OnClientClick="if ($('.txtValue').val()
!= '1') { $('.txtValue').val('1'); alert('Warning: Please enable pop-ups for
this site!'); }" />
This method survives ajax and postbacks.
此方法在 ajax 和 postbacks 中仍然存在。
Cheers
干杯