2010-03-01 105 views
2

我有一個綁定到ListView控件的SQLDataSource,但我想將部分綁定記錄放入HTML TITLE屬性中。下面是我想改變,因此它可以使用eval根據數據的內容來構建一個動態的TITLE我隱藏文件:如何在代碼隱藏中使用Eval來設置Page.Title

Public Partial Class zShowAd 
Inherits System.Web.UI.Page 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
     Me.Page.Title = " Dynamically set in ASPX page" 
     'how to use Eval here instead of the above constant ??  
    End Sub 
End Class 

下面是相應的.aspx文件:

<%@ Page Language="vb" AutoEventWireup="false" MasterPageFile="~/zSEO.master" 
    CodeBehind="zShowAd.aspx.vb" Inherits="Zipeee.zShowAd" %> 
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> 
<div> 
    <asp:ListView ID="ShowAd" runat="server" DataSourceID="aPosting"> 
    <LayoutTemplate> 
     <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder> 
    </LayoutTemplate> 
    <ItemTemplate> 
    <div> 
    <div id="wrapper"> 
     <div id="header"></div> 
     <div id="main"> 
      <div id="nav"> AdID: <%#Eval("AdID")%></div> 
      <div id="extras">Price: <%#Eval("Price")%></div> 
      <div id="content">  <%#Eval("AdDesc")%></div> 
     </div> 
     <div id="footer"></div> 
    </div> 
    </div> 
    </ItemTemplate> 
</asp:ListView> 

<asp:sqldatasource runat="server" id="aPosting" 
     ConnectionString="<%$ ConnectionStrings:ZIPeeeConnectionString2 %>" 
     SelectCommand="spGetAdByID" SelectCommandType="StoredProcedure"> 
     <SelectParameters> 
      <asp:QueryStringParameter Name="AdId" QueryStringField="a" Type="String" /> 
     </SelectParameters> 
    </asp:sqldatasource> 
</div> 
</asp:Content> 

回答

8

你可以通過把地方下面你的ListView的ItemTemplate模板裏面調用頁面的代碼的方法(子)背後:

<%# SetPageTitle(Eval("SomeProperty")) %> 
在你的代碼

那麼後面(對不起它在C#):

protected void SetPageTitle(object title) 
{ 
    this.Title = title.ToString(); 
} 

另外,您也可以通過完整的數據項,而不是隻有一個屬性:

<%# SetPageTitle(Container.DataItem) %> 

更新(回答您的評論):

<%# ... %>是這樣稱爲數據綁定表達式。它僅適用於數據綁定控件(在您的示例中爲ListView),並且它始終與當前記錄一起工作(通常,您在像ListView這樣的數據綁定控件中顯示多條記錄)。

因此,當您使用<%# Eval("Price") %>時,顯示的是當前記錄的「價格」列的值。如果您的查詢將返回多個記錄,那麼這將針對每條記錄執行,並且在設置頁面標題時(如上所示),頁面的標題將是最後一條記錄的值。

另一方面,<%= ... %>,只是一個正常的服務器端代碼片段(不知道是否有一個特定的名稱),它不知道數據綁定上下文(例如哪個是當前的記錄)。

請參閱以下問題了解更多詳情:When should I use # and = in ASP.NET controls?

+1

非常感謝。我搜索了很多,從來沒有找到一個很好的解釋,爲什麼這個語法: <%#SetPageTitle(Eval(「SomeProperty」))%> 與此語法: <%SetPageTitle(Eval(「SomeProperty」)) %> 來自經典的ASP背景,第二種形式似乎確定。是否存在#(是稱爲綁定符號?),因爲語句包含Eval? – 2010-03-03 13:37:50

+0

@John:我試圖解釋更新後的答案中的差異。 – M4N 2010-03-03 15:10:27

+2

多麼好的解釋!謝謝。 – 2010-03-03 16:46:52