您对<%=...%>
语法的看法基本正确。这是引擎盖下发生的事情的示例:
<script runat="server">
public string SomeProperty { get { return "Hello World!"; } }
</script>
<form id="form1" runat="server">
<%= SomeProperty %>
<div>
<asp:Label ID="Label1" runat="server" Text="<%= SomeProperty %>"></asp:Label>
</div>
</form>
对其进行解析并创建以下 C# 代码(我已对其进行了一些简化):
private Label @__BuildControlLabel1()
{
Label @__ctrl = new Label();
this.Label1 = @__ctrl;
@__ctrl.ApplyStyleSheetSkin(this);
@__ctrl.ID = "Label1";
@__ctrl.Text = "<%= SomeProperty %>";
return @__ctrl;
}
private void @__Renderform1(HtmlTextWriter @__w, Control parameterContainer)
{
@__w.Write( SomeProperty );
@__w.Write("\r\n <div>\r\n ");
parameterContainer.Controls[0].RenderControl(@__w);
@__w.Write("\r\n </div>\r\n ");
}
<%#...%>
以下是语法背后发生的事情的示例:
<script runat="server">
public string SomeProperty { get { return "Hello World!"; } }
protected void Page_Load(object sender, EventArgs e) { Label1.DataBind(); }
</script>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="<%# SomeProperty %>"></asp:Label>
</div>
</form>
生成此代码:
private Label @__BuildControlLabel1()
{
Label @__ctrl = new Label();
this.Label1 = @__ctrl;
@__ctrl.ApplyStyleSheetSkin(this);
@__ctrl.ID = "Label1";
@__ctrl.DataBinding += new System.EventHandler(this.@__DataBindingLabel1);
return @__ctrl;
}
public void @__DataBindingLabel1(object sender, EventArgs e)
{
Label dataBindingExpressionBuilderTarget = ((Label)(sender));
Page Container = ((Page)(dataBindingExpressionBuilderTarget.BindingContainer));
dataBindingExpressionBuilderTarget.Text = System.Convert.ToString( SomeProperty , System.Globalization.CultureInfo.CurrentCulture);
}
如您所见,该<%=...%>
语法可以在服务器控件的属性之外使用,以直接呈现返回值。另一方面,该<%#...%>
语法为标签的 DataBinding 事件生成事件处理程序。此事件将标签属性的值设置为 SomeProperty 的值。每当调用 DataBind 方法时都会触发 DataBinding 事件,这就是我将该调用添加到 Page_Load 事件的原因。
希望这将帮助您了解它们之间的区别。