How to use ASP.NET <%= tags in server control attributes?

In my code i am using something like this easily but in the databound control like ListView Item template

 <asp:HyperLink ID="EditAction" class="actionLinks" Visible='<%#Eval("IsTrue").ToString() != "True"%>' runat="server" NavigateUrl='<%# Eval("ContentId","/articles/edit.aspx?articleid={0}")%>' />

But when i tried to use outside the databound control using <%# .. %>, it simply doesn't work.

You can easily do with

<a href="<%=myHref%>">My href</a> 

But for server controls, and outside of databound control. We need to call DataBind() in pageload event explicitly

<asp:Hyperlink ID="aa" NavigateUrl='<%#myHref%>' >

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.


you can do this

 <asp:Label ID="Label1" runat="server" ><%= variable%></asp:Label>

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();
}

Tags:

Asp.Net

Tags