使用runat =“server”访问HTML元素中的foreach变量

时间:2012-04-17 20:02:12

标签: c# asp.net .net data-binding

我有一个UserControl,其中包含一个包含照片列表的产品列表的属性。在.ascx我有DIV作为所有照片的容器。这就像现在一样。

<% 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属性。这不起作用,因为它无法解析来自product循环的foreach变量。似乎runat="server"使得来自foreach循环的变量不可访问,这是没有意义的,因为循环也必须在服务器上运行。

问题:
当元素具有foreach时,如何访问.as*x文件中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...
}

3 个答案:

答案 0 :(得分:2)

为什么不在创建div之前检查照片的计数?

<% foreach (var product in Products) { %>
    <div class="product">
        <% if (product.Photos.Count > 0) { %>
            <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>
<% } %> 

答案 1 :(得分:1)

您可以通过测试照片的<div>并设置其css样式来隐藏Count

<div class="product-photos" style="<%= product.Photos.Count == 0 ? "display=none;" : "" %> ">

这仍会创建<div>,但它会在页面上“隐藏”。

编辑:关于使用托管控件的问题,例如asp:Panel将呈现<div>。您必须根据您检索到的数据在User Control Load event期间动态创建控件,这将涉及在您的用户控件上添加child controls

答案 2 :(得分:0)

下午好,您可以尝试使用jquery为您处理此问题,可能会这样:

 $(function() {
      $('.product-photos').each(function() {
           var div = $(this);
           if ($(div).find('img').length === 0)
                div.hide();
      });
 });

这还没有经过测试,但我相信它应该让你去。