Search code examples
asp.netternary-operatorasp.net-session

ASP.NET ternary operator on the Session variable


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.


Solution

  • 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;