1

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

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by __avd
0

This should work fine:

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

Doesn't it?

2

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

Edited by __avd: n/a

Votes + Comments
provided a clear, precise and correct solution.
0

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 %>' />
1

>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") %> .

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.