我正在尝试使用三元运算符将 css 类添加到 TextBox
如果Session
变量包含特定值:
<asp:TextBox runat="server" ID="txtMyTextBox" Width="70px"
class='role-based jsSpinner <%= Session["MyVariable"] == "MyValue" ? "ui-widget-content ui-corner-all" : "" %>' />
我可以确认MyVariable
有MyValue
值,但是,当我运行应用程序时,该类不会被应用。我发现了其他几个类似的问题,但它们都使用三元运算符作为绑定(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/