ASP.NET/特殊用途符號

維基教科書,自由的教學讀本

尖括號 百分號 等號[編輯]

<%=  %>  

用於解析表達式,顯示伺服器端後台的信息。如:

<div> 
<h1>Hello World</h1> 
<p><%= ShowHelloWorld() %></p> 
</div>

尖括號 百分號 井號[編輯]

 <%# %> 

數據綁定,如:

<%# DataBinder.(Container.DataItem, "ClassName") %>
 <asp:DataList ID="dl" runat="server"> 
<ItemTemplate> <%# DataBinder.(Container.DataItem, "ClassName") %> 
</ItemTemplate> 
</asp:DataList>

尖括號 百分號 @[編輯]

<%@ %> 

表示:引用(page指令 )。也可用來導入後台命名空間。如:

<%@ Page Language="C#"   CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ import namespace="system.data">

<%@ Register tagprefix="my" namespace="MyNamespace" %>
<my:CustomControl runat=server />

//引用一个控件
<%@ Reference Control="MyControl.ascx" %>
<%  MyControl ctrl = (MyControl) Page.LoadControl("MyControl.ascx");
    ctrl.CustomProperty = "..."; //REFERENCE directive is needed to access property
%>

註冊一個控件,可以在頁面佈局文件中直接使用它。

引用一個控件後,可以在後台代碼文件中編程使用它

 MyControl m=new MyControl;
 //或者:
 MyControl m1=(MyControl)LoadControl("MyControl.ascx") ;  
 Controls.Add(m);

尖括號 百分號[編輯]

<% %> 

在頁面中嵌入伺服器代碼塊。塊中的代碼可以為編程語句,並調用當前頁類中的函數。嵌入代碼塊在頁面呈現時被執行。例如:

<tr> 
<td height="20"> 
<div align="center">类别:</div> 
</td> 
<td height="9">&nbsp; 
<%function();%> 
</td> 
</tr>

尖括號 百分號 美元號[編輯]

<%$ %>用來綁定web.config里的字符串(鍵值對)

如:

<asp:TextBox runat="server" ID="cc" Text="<%$ ConnectionStrings:pubs%>"></asp:TextBox>
在web.config中:
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <connectionStrings>
    <add name="pubs" connectionString="Server=.;database=pubs;uid=sa;pwd=" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

尖括號 百分號 冒號[編輯]

<%: %>是ASP.NET4.0中新加入的綁定方式,常用於MVC中,但普通webform中也可使用。功能是對綁定的值進行一下編碼。因此以下兩者是等同的:

 <%= Server.HtmlEncode("<b>test</b>") %>
 <%: "<b>test</b>" %>;