ASP.NET ternary operator on the Session variable

1.3k Views Asked by At

I'm trying to use the ternary operator to add a css class to a TextBox if the Session variable contains a particular value:

<asp:TextBox runat="server" ID="txtMyTextBox" Width="70px"
  class='role-based jsSpinner <%= Session["MyVariable"] == "MyValue" ? "ui-widget-content ui-corner-all" : ""  %>' />

I can confirm that MyVariable has the MyValue value, however, when I run the application, the class doesn't get applied. I found several other similar questions but they all use the ternary operator for a binding expression (using <%# %>) and not for evaluating the Session variable. I feel like I'm missing something obvious. Any help is appreciated.

2

There are 2 best solutions below

9
On BEST ANSWER

Inline expressions are not parsed in attributes for controls with runat="server". However, you can use data bind expressions.

Check this answer for info about major difference between <%= %> and <%# %> syntax.

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        DataBind();
    }

    string Foo()
    {
        return (string)Session["MyVariable"] == "MyValue" ? "ui-widget-content ui-corner-all" : "";
    }
</script>

<asp:TextBox runat="server" CssClass='<%# Foo() %>' />

Also you try to compare object reference and string reference. Need to cast the object to string to make the equals operator work.

bool test1 = (string)Session["MyVariable"] == "MyValue";

bool test2 = String.Compare((string)Session["MyVariable"], "MyValue") == 0;

object myString = 1.ToString();

// false
// Warning: Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
bool bad = myString == "1";

// true
bool good1 = (string)myString == "1";

// true
bool good2 = String.Compare((string)myString, "1") == 0;
3
On

Your code is fine, no cast is needed. I bet the string is not in the session. Use your debugger. This worked for me in VS 2008 C#

<%Session["foo"] = "bar"; %>
<div class='<% = Session["foo"] == "bar" ? "yes":"no" %>'>