0

Aim: To add a session to the ASP button so I can change the CSS value based on a set of rules.

Code so far:

<asp:Button ID="btnMyDetails" runat="server" Text="My Details" CssClass="<%=Session.Item('btnMyDetails').ToString()%>" CausesValidation="False" />

Error:

The above code tries to run the session as text and not a session. I've tried with both " and ' around.

History:

I have a working version where I use lists but would like to remove this extra coding:

<li class="<%=Session.Item("btnMyDetails").ToString()%>"
<asp:Button ID="btnMyDetails" runat="server" Text="All" CssClass="Button" /></li>
indofraiser
  • 1,014
  • 3
  • 18
  • 50
  • duplicate question http://stackoverflow.com/questions/370201/why-will-expressions-as-property-values-on-a-server-controls-lead-to-a-co – Waqas Raja Mar 09 '16 at 08:36
  • I changed the code to but that does not work. The question you refer to is about visible and not visible, not CSS classes. – indofraiser Mar 09 '16 at 08:44

2 Answers2

1

Use Following:

<asp:Button ID="btnMyDetails" runat="server" Text="My Details"  CssClass='<%#Session["btnMyDetails"].ToString()%>' CausesValidation="False"     OnClick="btnMyDetails_Click" />

When you set value for your Session variable at that time don't forget to call DataBind method of Button that you created. if you do not call DataBind method nothing will get assigned.

for example on page_load method you set your session variable to some value,

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["btnMyDetails"] = "firstClass";
        btnMyDetails.DataBind();
    }

'firstClass' will be assigned as cssClass to your button.

After that if you change value of your session variable then again call DataBind method of that button. Example of Button Click event is given

    protected void btnMyDetails_Click(object sender, EventArgs e)
    {
        Session["btnMyDetails"] = "NewClass";
        btnMyDetails.DataBind();
    }

Now 'NewClass' will get assigned.

Vijay Gite
  • 26
  • 3
0

I'd go a few steps to avoid depending on your session that way, tying to directly to a property of a control. At the very least I'd call a property like MyDetailsButtonCssClass in the Page class and put the logic there.

Is there a particular condition that's being changed in session that you could use to determine the class instead of putting the class name directly in session? Otherwise you could find yourself with one logical condition that changes but multiple class names that get stored in session.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62