我有一個UserControl,它具有包含照片列表的產品列表的Property。在.ascx
我有一個DIV
作爲所有照片的容器。這是現在的作品。使用runat =「server」訪問HTML元素中的foreach變量
<% foreach (var product in Products) { %>
<div class="product">
<div class="product-photos">
<% foreach (var photo in product.Photos) { %>
<img src="<%= photo.Url %>" alt="<%= product.Name %> Photo"/>
<% } %>
</div>
<!-- Other product markup/data here... -->
</div>
<% } %>
如果沒有照片,我現在試圖隱藏DIV
。我的想法是讓「產品照片」DIV
有一個runat="server"
並給它一個Visible
屬性。這是行不通的,因爲它無法解決來自我的foreach
循環的變量product
。看起來runat="server"
使foreach
循環中的變量無法訪問,這是沒有意義的,因爲循環也必須在服務器上運行。
問:
如何訪問一個.as*x
文件中的foreach
循環定義的變量時,該元素有一個runat="server"
?這甚至有可能嗎?如果不是,那麼完成我想要的任何替代方法是什麼?
ProductsControl.ascx.cs
public partial class ProductsControl: UserControl
{
public IList<Product> Products { get; set; }
}
Product.cs
public class Product
{
public IList<Photo> Photos { get; set; }
// Other properties here...
}
有一個答案發布了一分鐘前有關使用'asp:DataList'而不是foreach循環。我嘗試對此發表評論,但在我能夠之前它已被刪除。誰添加了答案,然後刪除它應該把它帶回來,它可能真的幫助我! – 2012-04-17 20:27:19