tags:

views:

151

answers:

5

Hi,

This works:

<span value="<%= this.Text %>" />

This doesn't work:

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

Why is that?

How can I make the second case work properly, i.e., set the label's text to the value of the "Text" variable?

+1  A: 

<asp:Label> is compiling at runtime and converting to html tags. You can set text with codebehind or like this:

<asp:Label id="Text1" runat="server" />
<% Text1.Text = this.Text;%>

UPD: Seems like my variant doesnt work, this is better:

protected void Page_Load(object sender,EventArgs e) 
{
    Text1.Text = this.Text;
}
x2
+1  A: 

You will need to set the value of the server control in code

First of all, assign an ID to the label control so you can access the control

<asp:Label ID="myLabel" runat="server" />

Then, in your Page_Load function, set the value of your labels 'Text' field

protected void Page_Load(object sender, EventArgs e)
{
    myLabel.Text = 'Whatever you want the label to display';
}

This function will be in your code behind file, or, if you are not using the code behind model, inside your aspx page you will need

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        myLabel.Text = 'Whatever you want the label to display';
    }
</script>

Good luck.

RR
+5  A: 

Use Data binding expressions

<asp:Label ID="Label1" runat="server" Text="<%# DateTime.Now %>" ></asp:Label>

Code behind,

protected void Page_Load(object sender, EventArgs e){
  DataBind();
}
adatapost
+1  A: 

I was already aware of the possibility of setting the value of server controls in code.

My question was if it's possible to avoid that somehow, in order to make the markup clearer (and more elegant, i would say).

jhrecife
A: 

Not sure how to mark this as such, but this is a bit of a duplicate. See this thread.

Just to add insult to injury, I don't think embedding code in to your markup will really make your markup any clearer or more elegant. :)

chevett