[英]How to store value from a textbox into a javascript variable in a asp.net vb.net application
[英]How to get value of application variable in JavaScript from asp.net?
我想訪問JavaScript中應用程序變量的值。 我怎樣才能做到這一點?
在代碼隱藏中聲明一個公共財產。
public string firstName = "Sanju";
像這樣在JavaScript中訪問它。
<script>
var myName;
function GetMyName()
{
myName = <%=this.firstName%>
}
</script>
要訪問會話狀態中的值,請使用它。
myName = '<%=Session["firstName"]%>'
要訪問“應用程序狀態”中的值,請使用它。
myName = '<%=Application["firstName"]%>'
您可以公開變量以使用javascript訪問。
在代碼后面。
public string YourVar = "hello";
在JavaScript中
alert("<%= YourVar %>");
請注意,發送響應后,服務器端變量的值將替換為生成的html / javascript。 如果要在頁面加載后通過javascript訪問它,則可能需要使用ajax調用來從服務器獲取值。
以下獲取呈現的控件的ClientID
//markup
<asp:TextBox ID="aTextBox" runat="server" />
<asp:TextBox ID="bTextBox" runat="server" />
<asp:TextBox ID="cTextBox" runat="server" />
//script
var Members =
{
aTextBox: $("#<%=aTextBox.ClientID %>"),
bTextBox: $("#<%=bTextBox.ClientID %>"),
cTextBox: $("#<%=cTextBox.ClientID %>")
}
嘗試會話...在您的課堂上進行一個會話(我假設您有一個通用課堂),並使用其引用在所需的任何頁面上進行訪問。 但是請記住,必須在使用前分配一個值。
例如,
下面是一個UserID會話。
public static int UserId
{
get
{
if (HttpContext.Current.Session["UserId"] != null)
return Convert.ToInt32(HttpContext.Current.Session["UserId"]);
else
return 0;
}
set
{
HttpContext.Current.Session["UserId"] = value;
}
}
首先,您必須在應用程序啟動后立即在會話中存儲價值。
User user = new user(); // consider you have a User class
protected void btnLogin_OnClick(object sender, EventArgs e)
{
_user.Username = this.txtUserName.Text;
_user.Password = this.txtPassword.Text;
if (_user.Validate())
{
General.UserID = _user.UserID; // here you are storing the id of logged in user
Response.Redirect("~/HomePage.aspx");
}
else
{
this.labelNotice.Text = "Invalid Username or Password";
}
}
要在javascript的任何頁面上訪問此會話的值,
<%@ Import Namespace="MyProject.Models" %>
<script type="text/javascript">
var myID;
function GetMyID() {
myID= '<%=General.UserId%>';
}
</script>
我導入了通用類,該通用類位於MyProject解決方案的“ 模型”文件夾中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.