Using Code Nuggets as property values

I have the following code

<asp:Content ID="Content1" runat="server">

<asp:Label runat="server" ID="Label1" Text="<%= MyHelperClass.Value%>"></asp:Label>    
<%= MyHelperClass.Value%>

</asp:Content>

The Label doesn’t work, it has the Text <%= MyHelperClass.Value%> the next row returns the expected value.

Question: can i use those code nuggets to set values of the property of an control?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Why it’s working outside and not with Control?

Well <%= %> is called Content Code Nuggets because they inject content in the html which is sent by server to browser. It does the work of Reponse.Write. We use this mainly to call any code written in code behind file for example, you have a simple method in your code behind:-

public string UserCity()
{
   return "London";
}

Then you can call it from aspx page like this:-

You live in <%= UserCity() %>.

Content code nuggets used to inject the html to response at the last in PreRender event and thus it’s called late binding. This is the main reason why it is NOT working with your control.

How to fix this?

You can use the data binding code nuggets (<%# %>). These are used with DataBound controls but you can force the Page’s DataBound or control’s DataBound method to bind your control like this:-

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

Call DataBind method in code behind:-

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Page.DataBind();
    }
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply