Is it possible t set a control's property in the markup using server tags? Specifically in this case I need to set it from a Session value, ideally something like this:

<asp:Label ID="Label1" runat="server" Text='<%= Session["value"] %>' />

Of course the above simply prints as literal text, rather than evaluating the expression.

I know I can do it in the code behind, but in the circumstances it would be a lot cleaner if I could somehow do it in the markup or "bind" the property to the Session value.

Open to ideas, any suggestions appreciated.

Cheers
/H

Recommended Answers

All 4 Replies

This should work fine:

<asp:Label ID="Label1" runat="server" Text="<%= Session["value"].ToString() %>" />

Doesn't it?

No! you can't use <%= %> (expression) with server controls.

Use Binding expression:

Markup:

<asp:Label ID="Label1" runat="server" Text='<%# Session["value"] %>' />

Code-behind

protected void Page_Load(object sender, EventArgs e)
    {
        Session["value"] = 100;
        Label1.DataBind();
    }
commented: provided a clear, precise and correct solution. +2

Thanks! That does exactly what I need.

I didn't realise you could call DataBind expressions on controls without a DataSource assigned.

Just in case this is useful/interesting to anyone else, I am also able to use this to restrict controls Enable/Visible properties based on security settings loaded into the Session at login time.
eg:

<asp:Button ID="btnDelete" runat="server" Text="Delete" Enabled='<%# Session["PermissionLevel"] > 3 %>' />

>I didn't realise you could call DataBind expressions on controls without a DataSource assigned.

Actually, you have assigned a single value as an "expression"; it is also known as simple data binding.

You must have to call DataBind() method in order to evaluate <%# Eval("expression") %> .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.