简体   繁体   English

如何在ASPX页面中访问变量?

[英]How to access to variable in ASPX page?

ASPX: ASPX:

<form id="form1" runat="server">
    <%
       int a = 25;
    %>
    <asp:Label ID="Label1" runat="server" 
         Text='<%#a %>'></asp:Label>
</form>

Code behind: 后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       DataBind();
    }
}

Error: 错误:

The name 'a' does not exist in the current context 名称“ a”在当前上下文中不存在

Found solution: 找到的解决方案:

ASPX: ASPX:

<form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" 
         Text="<%#a %>"></asp:Label>
</form>

Code behind: 后面的代码:

public int a;
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      a = 25;
      DataBind();
   }
}

This way will work.. ASPX: 这种方式将起作用.. ASPX:

<form id="form1" runat="server">
         <asp:Label ID="Label1" runat="server"></asp:Label>
</form>

code behind: 后面的代码:

public int a;
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      a = 25;
    Label1.Text=a.ToString();
   }
}

something to note, is that the aspx file is compiled to a class by the the System.Web.UI.Page class which implements IHttpHandler, the created class inherit the aspx.cs/aspx.vb, which explain the inherits in the <%@ Page %> directive, and by logic, you cannot reference a variable declared in aspx code nugget in code behind. 一些需要注意的是,ASPX文件是由它实现了IHttpHandler,所创建的类继承的aspx.cs / aspx.vb,这说明在<%继承的System.Web.UI.Page类编译成类@ Page%>指令,根据逻辑,您不能在后面的代码中引用在aspx代码块中声明的变量。
As a work around, you can declare protected members in code behind and access those from code nuggets. 解决方法是,可以在后面的代码中声明protected成员,然后从代码块访问这些成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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