这个问题是我在尝试回答另一个问题时注意到的结果.现在我很好奇知道为什么<asp:TextBox runat="server" Visible="<%= true %>" />
会导致编译错误,而不是像我期望的那样导致可见的TextBox.
从我迄今发现的内容来看,<%= %>
表达式并没有像我一直认为的那样被翻译成文字控件.但是,在呈现页面时,它会被评估并直接写入HtmlTextWriter.但显然解析器(我不确定这是将ASP.NET标记转换为.NET代码的部分的正确术语)<%= %>
在将它们用作服务器控件的属性值时甚至不会尝试计算表达式.它只是将它用作字符串.我猜这就是为什么我收到错误消息:无法从'Visible'属性的字符串表示'<%= true%>'创建'System.Boolean'类型的对象.
如果我改为抛弃runat ="server"并将其<%= %>
与常规的html-markup 相结合,如下所示:
<input type="button" id="Button1" visible='<%= true %>' />
Run Code Online (Sandbox Code Playgroud)
然后解析器只是在表达式之前和之后将块拆分为部分,然后将其写入render方法中的HtmlTextWriter.像这样的东西:
__w.Write("<input type=\"button\" id=\"Button1\" visible='");
__w.Write(true);
__w.Write("' />");
Run Code Online (Sandbox Code Playgroud)
作为我注意到的最后一件事...当我尝试<%# %>
+ Control.DataBind(),然后我得到我期望的.它将控件数据绑定时使用的表达式挂钩,但与<%=%>表达式不同,生成的代码实际上会计算<%# %>
表达式的内容.解析器最终生成以下内容:
[DebuggerNonUserCode]
private Button __BuildControldataboundButton()
{
Button button = new Button();
base.databoundButton = button;
button.ApplyStyleSheetSkin(this);
button.ID = "databoundButton";
button.DataBinding += new EventHandler(this.__DataBindingdataboundButton);
return button;
}
public void __DataBindingdataboundButton(object sender, EventArgs e)
{ …
Run Code Online (Sandbox Code Playgroud)