简体   繁体   中英

asp.net databind label control text to property of page baseclass

Why is TestString is always empty when I try to output it into my Label?

Base class for all asp.net pages

public class PageBase : System.Web.UI.Page
{
    protected string TestString { get; set; }
}

protected override void OnPreInit(EventArgs e)
{
TestString = "test string";
}

asp.net page that derives from PageBase and uses a master page.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:Label ID="lblContent" runat="server" Text="<%# this.TestString %>" />
</asp:Content>

You need to call the DataBind() method.

In page_load handler,

TestString="Testing a property";
lblContent.DataBind();
//or
DataBind();

EDIT

The code below doesn't actually work—I tested it, just not well. What OP was really looking for was:

<div id="lblContent"><%= this.TestString %></div>

I think you need to change this

<asp:Label ID="lblContent" runat="server" Text="<%# this.TestString %>" />

to this

<asp:Label ID="lblContent" runat="server" Text="<%= this.TestString %>" />

<%# just runs code, but doesn't output anything. <%= will output whatever is inside those tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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