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>" %>;