asp.net中的<%%>形式的詳細用法總結

來源:互聯網
上載者:User
一. <%%>
這種格式實際上就是和asp的用法一樣的,只是asp中裡面是vbscript或
者javascript代碼,而在asp.net中用的是.net平台下支援的語言。特別
注意:伺服器控制項中不能包含<%%>的文法,否則出錯。如下,我們可以
在.aspx頁面裡出現如下代碼:

 

1 <% 
2   int a = 2;
3   int b = 3;
4   int c = a + b;
5   Response.Write(c);
6  %>

  二. <%#%>
這種格式是asp.net下特有的,它是控制項資料繫結的文法,且必須要調用該

控制項的DataBind()方法才執行(或者整個頁面Page.DataBind()也就是對

所得控制項都調用DataBind()方法)特別。

 注意:只有伺服器控制項才能用<%#%>的文法  aspx.cs代碼如下:

1 <div>
2 Server Control:<asp:TextBox runat="server" Text="<%#text%>"></asp:TextBox><br /><!--Server Control-->
3 Client Control:<input type="text" value="<%#text%>" /><!--Client Control-->
4  </div>
代碼 
protected string text;//注意這裡必須申明為public或protected,否則aspx頁面(子類)無法訪問
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.text = "aaaaaaaaaaaaa";
this.TextBox1.DataBind();//或this.DataBind();
}
}
三. <%=%>
這種格式經常用到的。 
<label ><%=DisplayStr()%></label><br />
<label runat="server"><%=DisplayStr()%></label>
aspx.cs代碼:
public string DisplayStr()//注意這裡必須要有傳回值,否則將會發生執行階段錯誤
{
return "bbbb";
}
四.<%$%>
主要用於引用外部資源
特別注意:1.綁定的只能是伺服器控制項
2.只能綁定到伺服器控制項的某個屬性上。
以下以擷取web.config資源來做執行個體:

 

代碼
<asp:TextBox runat="server" ID="cc" Text="<%$ConnectionStrings:pubs%>"></asp:TextBox>
web.config檔案如下:
<connectionStrings><add name="pubs" c providerName="System.Data.SqlClient"/></connectionStrings>

 這樣就能正常運行。
如果修改aspx中的檔案:使用用戶端的控制項
<input type="text" value="<%$ConnectionStrings:pubs%>"/>
或者:不綁定到伺服器控制項的某個屬性上
<asp:TextBox runat="server" ID="cc"><%$ConnectionStrings:pubs%></asp:TextBox>
運行都會出現相同的錯誤:
"分析器錯誤資訊:不允許使用類似"<%$ConnectionStrings:pubs%>"類似的文本運算式,請改用……

最後強調:
<%#%>只針對的是伺服器控制項的資料繫結,因此不能同<%=%>和<%%>混合使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.