GAT
GAT

Reputation: 115

Why can't I set the asp:Label Text property by calling a method in the aspx file?

Can somebody please explain this to me:

I have a label and I want to be able to set the Text property by calling a method in the aspx file. It works fine if I set the property in code behind, but I really want to set this property in the aspx file.

I have tried a couple of things, but what I expected to work was this:

<asp:Label ID="Label1" runat="server" Text=<%# GetMyText("LabelText") %> />

I get no errors when doing this, but my method is never called and the Text property is left empty.

Is it not possible to set property values to server side controls directly in the aspx without using resources or use hard coded values?

Update: My first try was:

<asp:Label ID="Label1" runat="server" Text=<%= GetMyText("LabelText") %> />

But that results in the following error:

Server tags cannot contain <% ... %> constructs.

Upvotes: 9

Views: 12084

Answers (3)

David
David

Reputation: 73554

Try this:

<asp:Label ID="Label1" runat="server" Text='<%= GetMyText("LabelText") %>' />

Edit

Yep. I was wrong. @Joe was right.


However, THIS works (and I'm not sure what the difference is):

 <asp:Label ID="Label1" runat="server"><%= GetMyText("LabelText") %></asp:Label>

CodeBehind:

protected string GetMyText(string input)
{
   return "Hello " + HttpUtility.HtmlEncode(input);
}

Upvotes: 0

Geoff
Geoff

Reputation: 4746

The sysntax you are looking for is <%= %> the # is for data binding. So your code should read:

<asp:Label ID="Label1" runat="server" Text='<%= GetMyText("LabelText") %>' />

EDIT: This answere is incrrect

I am leaving this answer here because lots of people agreed with me that this is infact the correct answer, but it will not work. This line of code will produce the following HTML output:

<span id="Label1"><%= GetMyText("LabelText") %></span>

Upvotes: 3

to StackOverflow
to StackOverflow

Reputation: 124696

The syntax =<%# ... %> is Data binding syntax used to bind values to control properties when the DataBind method is called.

You need to call DataBind - either Page.DataBind to bind all the controls on your page, or Label1.DataBind() to bind just the label. E.g. add the following to your Page_Load event handler:

    if (!IsPostBack)
    {
        this.DataBind();
        // ... or Label1.DataBind() if you only want to databind the label
    }

Using Text='<%= GetMyText("LabelText") %>' as others have proposed won't work as you'll find out. This syntax is inherited from classic ASP. It can be used in some circumstances in ASP.NET for inserting dynamic values in static HTML, but can not be used for setting propeties of server controls.

Upvotes: 12

Related Questions