如果TextBox变量包含特定值,则尝试使用三元运算符将css类添加到Session:
<asp:TextBox runat="server" ID="txtMyTextBox" Width="70px"
class='role-based jsSpinner <%= Session["MyVariable"] == "MyValue" ? "ui-widget-content ui-corner-all" : "" %>' />我可以确认MyVariable具有MyValue值,但是,当我运行应用程序时,类不会被应用。我发现了其他几个类似的问题,但它们都使用三元操作符作为绑定表达式(使用<%# %>),而不是计算会话变量。我觉得我漏掉了一些显而易见的东西。任何帮助都是非常感谢的。
发布于 2014-08-12 15:35:33
对于带有runat="server“的控件,在属性中不解析内联表达式。但是,您可以使用数据绑定表达式。
查看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;发布于 2014-08-12 15:59:08
您的代码很好,不需要强制转换。我打赌这个字符串不在会话中。使用调试器。这在VS 2008 C#中对我起了作用。
<%Session["foo"] = "bar"; %>
<div class='<% = Session["foo"] == "bar" ? "yes":"no" %>'>https://stackoverflow.com/questions/25268381
复制相似问题