I have a case that I need to set the Text property for an asp label in the aspx page not from code behind. More exactly, I need to set a value to asp control in aspx page and this value is set by a property in the same page code behind.
我有一个案例,我需要在aspx页面中为asp标签设置Text属性,而不是从后面的代码。更确切地说,我需要在aspx页面中为asp控件设置一个值,并且该值由后面相同页面代码中的属性设置。
so I need to use an expression to do that like:
所以我需要使用表达式来做到这一点:
<asp:Label Text="<%= MyProperty %>" ..../>
I use:
我用:
<%= MyProperty %> doesn't work.
<%# MyProperty %> doesn't also.
3 个解决方案
#1
23
Default.aspx.cs
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
public string CustomTitle = "This Is Title";
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
}
Default.aspx
Default.aspx的
<asp:Label Text='<%#CustomTitle %>' runat="server" />
#2
12
You have to treat regular HTML and WebControls differently:
您必须以不同方式处理常规HTML和WebControl:
regular HTML:
常规HTML:
Using <%= ... %>
is sufficient:
使用<%= ...%>就足够了:
<span><%= MyProperty %></span>
WebControls (stuff starting with <asp:...>):
WebControls(以
<asp:Label Text='<%# MyProperty %>' />
In this case, you also have to call Me.DataBind()
(VB) or this.DataBind();
(C#) in your codebehind, since <%# ... %>
are data binding expressions.
在这种情况下,您还必须调用Me.DataBind()(VB)或this.DataBind();代码隐藏中的(C#),因为<%#...%>是数据绑定表达式。
#3
3
Page.DataBind();
Do you call this in your code? It binds all variables set in code to your page.
你在代码中叫这个吗?它将代码中设置的所有变量绑定到您的页面。
#1
23
Default.aspx.cs
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
public string CustomTitle = "This Is Title";
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
}
Default.aspx
Default.aspx的
<asp:Label Text='<%#CustomTitle %>' runat="server" />
#2
12
You have to treat regular HTML and WebControls differently:
您必须以不同方式处理常规HTML和WebControl:
regular HTML:
常规HTML:
Using <%= ... %>
is sufficient:
使用<%= ...%>就足够了:
<span><%= MyProperty %></span>
WebControls (stuff starting with <asp:...>):
WebControls(以
<asp:Label Text='<%# MyProperty %>' />
In this case, you also have to call Me.DataBind()
(VB) or this.DataBind();
(C#) in your codebehind, since <%# ... %>
are data binding expressions.
在这种情况下,您还必须调用Me.DataBind()(VB)或this.DataBind();代码隐藏中的(C#),因为<%#...%>是数据绑定表达式。
#3
3
Page.DataBind();
Do you call this in your code? It binds all variables set in code to your page.
你在代码中叫这个吗?它将代码中设置的所有变量绑定到您的页面。