2011-06-03 70 views
2

我有一個頁面,其中列出了幾家酒店,並且爲每個酒店列出了用戶選擇的每個日期的價格。嵌套中繼器 - 從子中繼器訪問父節點中的控制器

我的HTML看起來像這樣:

<table> 
<asp:Repeater ID="rptrHotels" runat="server"> 
    <ItemTemplate> 
     <tr><td><%# Eval("HotelName") %></td></tr> 
     <tr> 
      <asp:Repeater ID="rptrHotelRates" runat="server" DataSource='<%# GetHotelRates(Container.DataItem) %>'> 
       <ItemTemplate> 
        <td> 
         <span class="date"><%# Eval("Date") %></span> 
         <span class="price">$<%# Eval("Price") %></span> 
        </td> 
       </ItemTemplate> 
      </asp:Repeater> 
      <td> 
       <span class="date">Total</span> 
       <span class="price">$<asp:Literal ID="litTotal" runat="server" /></span> 
      </td> 
     </tr>     
    </ItemTemplate> 
</asp:Repeater> 
</table> 

我的後臺代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     DateTime startDate = Request.QueryString["StartDate"]; 
     DateTime endDate = Request.QueryString["EndDate"]; 

     List<Hotel> hotels = GetHotels(startDate, endDate); 
     rptrHotels.DataSource = hotels; 
     rptrHotels.DataBind(); 
    } 
} 


protected List<Rate> GetHotelRates(object item) 
{ 
    DateTime startDate = Request.QueryString["StartDate"]; 
    DateTime endDate = Request.QueryString["EndDate"]; 
    Hotel hotel = (Hotel)item; 

    List<Rate> rates = GetRates(hotel, startDate, endDate); 

    decimal total = (from r in rates 
        select r.Price).Sum(); 

    return rates; 
} 

在我GetHotelRates()函數,我總結了所有的速度越來越總價價格。但我需要以某種方式將該值放在litTotal中,該值位於子轉發器之外,但位於父轉發器之內。

我該怎麼做?

+0

你明白了嗎? – ashelvey 2011-06-05 20:33:27

回答

5

在你的項目綁定事件做這樣的事情:

((Literal)((Repeater)sender).Parent.FindControl("litTotal")).Text; 

你可能需要做父另投它得到一箇中繼器,但我不知道。

+0

我的GetHotelRates()函數中沒有'object sender'變量。我需要做些什麼來補充? – Steven 2011-06-03 21:09:32

+0

如果你有一個ItemDataBind事件,你只會得到。基本上,每當一個物品被數據綁定時,就會使用上面的那一行代碼。 – 2011-06-03 23:26:05

+0

我從來沒有想到我可以將發件人作爲容器中繼器! +1代碼的一大堆。 – seanxe 2012-04-13 15:33:50

0

你總是可以嘗試一些NamingContainer.Parent.Parent ....的FindControl(誇張)的魔法,但一個更清潔的方式做到這一點是隻創建一個單獨的方法來獲取您的總:

protected decimal GetHotelTotal(object item) 
{ 
    Hotel hotel = (Hotel)item; 

    List<Rate> rates = GetRates(hotel, startDate, endDate); 

    decimal total = (from r in rates 
       select r.Price).Sum(); 
    return total; 
} 

並在你的文字中稱呼:

<asp:Literal ID="litTotal" runat="server" Text="<%# GetHotelTotal(Container.DataItem) %>" /> 
+0

當然,如果運行GetRates的代價很高,您可能需要考慮稍微有點不同的設計,既可以保留呼叫的價值,也可以使其成爲Hotel對象的一部分,因此它已經存在。 – ashelvey 2011-06-03 20:49:39

+0

我想我其實更喜歡第二種方法..我會添加一個屬性列表 HotelRates到您的GetRates填充的酒店。然後,您不必在DataBinding時間混淆這一點,並且您已準備好將所有東西都乾淨地使用。 – ashelvey 2011-06-03 20:51:51