Session 变量上的 ASP.NET 三元运算符

标签 asp.net ternary-operator asp.net-session

我正在尝试使用三元运算符将 css 类添加到 TextBox如果Session变量包含特定值:

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

我可以确认MyVariableMyValue值,但是,当我运行应用程序时,该类不会被应用。我发现了其他几个类似的问题,但它们都使用三元运算符作为绑定(bind)表达式(使用 <%# %> ),而不是用于评估 Session 变量。我觉得我错过了一些明显的东西。任何帮助表示赞赏。

最佳答案

对于带有 runat="server"的控件,内联表达式不会在属性中进行解析。但是,您可以使用数据绑定(bind)表达式。

检查this answer有关 <%= %><%# %> 语法之间主要差异的信息。

<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() %>' />

您还尝试比较对象引用和字符串引用。需要将对象转换为字符串以使等于运算符起作用。

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;

关于Session 变量上的 ASP.NET 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25268381/

相关文章:

lua逻辑运算符/a?b :c operator

asp.net-session - 如何在 ASP.NET session Cookie 上设置安全标志?

c# - 在 Web 应用程序中使用条码渲染框架生成的条码下的条码编号

applescript - AppleScript 是否有条件(三元)运算符的等价物?

c# - 对 'var' 关键字和三元运算符有疑问? :

c# - session ID 不够随机 - ASP.NET

asp.net-mvc - 我可以将 session 状态存储在 ASP.NET MVC 应用程序的现有 SQL Azure DB 中吗?

c# - 动态创建动态 RadioButtonsList

javascript - 创建独立的职位发布组件

c# - 如何删除在 ASP.NET MVC4 SimpleMembership 中具有角色的用户?