内联表达式不会在具有 runat="server" 的控件的属性中解析。但是,您可以使用数据绑定表达式。
检查此答案以获取有关<%= %>和<%# %>语法之间主要区别的信息。
<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;