[英]How to call code behind function from label.text in asp.net
I am trying to call a function defined in code behind from Label.Text but it's not working. 我试图从Label.Text后面调用代码中定义的函数,但是它不起作用。 Here is the code... code in .aspx file
这是代码... .aspx文件中的代码
<asp:Label runat="server" Text='<%# GetPagingCaptionString() %>' ID="pagenumberLabel"></asp:Label>
code block from code behind 代码块从后面的代码
public string GetPagingCaptionString()
{
int currentPageNumber = Convert.ToInt32(txtHidden.Value);
int searchOrderIndex;
if (int.TryParse(Convert.ToString(Session["searchOrderIndex"]), out searchOrderIndex))
{
return string.Format("{0} to {1} orders out of {2}", (currentPageNumber * 20) + 1,
(currentPageNumber + 1) + 20, GetItemsCount(searchOrderIndex.ToString()));
}
return String.Empty;
}
Can anyone tell me what's wrong here. 谁能告诉我这是怎么回事。
Unless you're using a template based control (such as <asp:Repeater>
or <asp:GridView>
) then you can't use inline code-blocks such as you have within a server-side control. 除非您使用基于模板的控件(例如
<asp:Repeater>
或<asp:GridView>
),否则不能使用服务器端控件中的内联代码块。
In other words, you can't have <%=%>
blocks within the attributes of server-side controls (such as <asp:Label>
). 换句话说,服务器端控件的属性(例如
<asp:Label>
)中不能包含<%=%>
个块。 The code will not be run and you will find the code is actually sent as part of the rendered HTML. 该代码将不会运行,您会发现该代码实际上是作为呈现的HTML的一部分发送的。 The exception is for databinding controls where
<%#%>
code-blocks are allowed. 唯一的例外是对于其中数据绑定控件
<%#%>
代码块是允许的。
You're better off in this situation setting the .Text
property in the code-behind itself. 在这种情况下,最好在代码本身后面设置
.Text
属性。
For instance in your page-load function.... 例如您的页面加载功能...。
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
pagenumberLabel.Text = GetPagingCaptionString();
}
}
If you add a Property to your page it will be accessible from your aspx like so: 如果将属性添加到页面,则可以通过aspx访问它,如下所示:
<asp:Label runat="server" Text='<%= PagingCaptionString %>' ID="pagenumberLabel" />
NB <%= %>
tag rather than <%# %>
which is used for databinding controls NB
<%= %>
标记而不是用于数据绑定控件的<%# %>
Codebehind: 代码背后:
public string PagingCaptionString {
get {
int currentPageNumber = Convert.ToInt32(txtHidden.Value);
int searchOrderIndex;
if (int.TryParse(Convert.ToString(Session["searchOrderIndex"]), out searchOrderIndex))
{
return string.Format("{0} to {1} orders out of {2}", (currentPageNumber * 20) + 1,
(currentPageNumber + 1) + 20, GetItemsCount(searchOrderIndex.ToString()));
}
return String.Empty;
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.