2014-09-21 35 views
0

ASPX:如何访问ASPX页面中的变量?

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

代码后面:

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

错误:

The name 'a' does not exist in the current context

+0

你也许试试吧'<%=a %>' – pushpraj 2014-09-21 03:09:27

+0

不行........ – 2014-09-21 03:11:05

+0

不行。 'Text ='<%#a %>'>' - 您只需将字符串设置为文本。我想,你需要在代码中完成它:'<%Label1.Text = a>%'。 – 2014-09-21 04:13:21

回答

0

实测溶液:

ASPX:

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

后面的代码:

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

这样会运行 ASPX:

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

后面的代码:

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

什么要注意的,就是aspx文件编译通过实现IHttpHandler的System.Web.UI.Page类来创建一个类,创建的类继承aspx.cs/aspx.vb,它解释了继承了中的<%@ Page%>指令,并且通过逻辑,您不能引用在代码后面的aspx代码块中声明的变量。
作为解决方法,您可以在后面的代码中声明protected成员,并访问代码块中的成员。

相关问题