I want to get property value from code behind
Asked Answered
B

3

14

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.

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.
Bangle answered 5/4, 2011 at 7:52 Comment(1)
When you debug, do you see if "MyProperty" is getting set in the code behind?Vincevincelette
E
29

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

<asp:Label Text='<%#CustomTitle %>' runat="server" />
Engraving answered 5/4, 2011 at 8:5 Comment(1)
it's work but and it write the value on the page as html span but not work if I use it inside the label tag !!Bangle
H
15

You have to treat regular HTML and WebControls differently:


regular HTML:

Using <%= ... %> is sufficient:

<span><%= MyProperty %></span>

WebControls (stuff starting with <asp:...>):

<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.

Hepler answered 5/4, 2011 at 8:45 Comment(3)
I do call to this.DataBind in page load but dosen't work with me !!?Bangle
<%= ... %> doesn't work for me in a head section which has runat="server" set. The output source shows <link rel="stylesheet" href="/css/custom.css?v=&lt;%=CSSVersionVal%>" media="screen" /> instead of <link rel="stylesheet" href="/css/custom.css?v=2" media="screen" />. I have CSSVersionVal set as a Property in the codebehind and it's outputting correctly everywhere else in the page, but not in the head.Ardell
I always forget the difference. Good explanation.Wojak
L
5
Page.DataBind();

Do you call this in your code? It binds all variables set in code to your page.

Letishaletitia answered 5/4, 2011 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.