我有一个用户控件,我在多个页面上使用它来显示有关某个对象的信息。每当我需要使用此用户控件时,我都会调用一个名为 Display 的方法(在用户控件上)并传入一些值。
public void Display(string name, List<Items> items)
{
// Set a few protected properties so I can display values from the aspx page
}
这工作正常,但现在我需要在 aspx 页面的 foreach 循环中使用此控件。
<% foreach (var c in Categories) { %>
<uc:ItemsControl runat="server"/>
<% } %>
类别对象具有我将以其他方式传递给 Display 方法的方法和属性。那么我该如何正确设置这些值呢?
我尝试将用户控件上的属性公开并以这种方式设置它们:
<uc:ItemsControl Items="<%# c.Items %>"
OtherProperty="<%# c.GetProperty() %>"
runat="server"/>
这不起作用,因为发送的属性是空的。如果我使用 <%= 那么它就不起作用并且实际上会抛出一个错误,因为它无法识别“c”(除非我取消 runat="server"然后它至少会编译,但它仍然无法工作.
执行此操作的正确方法是什么?
编辑:此外,转发器控件可能会使数据绑定(bind)更容易,但我宁愿避免使用任何 .NET 控件。
最佳答案
在 WebForms 页面中,通常使用 DataBinding 来处理这种情况。您可以使用 Repeater 而不是 foreach 循环控件,将其 DataSource 属性设置为 <%#Categories%>
, 然后在上面的后一个示例中使用数据绑定(bind)语法,除了 c
之外, 你需要投 Container.DataItem
到您控件中的正确类型。像这样:
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
CategoriesList.DataBind();
}
class Category
{
public string CategoryName { get; set; }
public string GetProperty() { return CategoryName; }
public string[] Items { get { return new string[] {CategoryName + " 1", CategoryName + " 2"}; } }
}
Category[] Categories = new Category[]
{
new Category { CategoryName = "Shorts" },
new Category { CategoryName = "Socks" },
new Category { CategoryName = "Shirts" },
};
</script>
<html>
<body>
<asp:Repeater runat="server" ID="CategoriesList" DataSource="<%# Categories %>">
<ItemTemplate>
<uc:ItemsControl
Items="<%# ((Category)(Container.DataItem)).Items %>"
OtherProperty="<%# ((Category)(Container.DataItem)).GetProperty() %>"
runat="server"/>
</ItemTemplate>
</asp:Repeater>
</body>
</html>
唯一需要注意的是,您需要在某处调用 Repeater 的 DataBind() 方法,通常在 Page_Load
中方法。
就我个人而言,我一直觉得数据绑定(bind)是一件痛苦的事情——转换和调用数据绑定(bind)的需要对我来说都比您在上面尝试的 foreach 方法更不自然。这可能是我最喜欢 ASP.NET MVC 的一点——您的 MVC View 可以更轻松地使用 foreach 迭代模型,这更简单,恕我直言。也就是说,如果您必须坚持使用 WebForms,则数据绑定(bind)与转换是阻力最小的途径。
顺便说一句,您上面的方法不起作用,因为:
runat=server ASP.NET 控件属性无法使用
<%= %>
语法——这只是有用的 用于纯文本输出,不用于 填写对象属性。使用数据绑定(bind)语法 (
<%# %>
) 绝对可以用来填充 在控制属性中,但你需要 将控件包装在数据绑定(bind)中 容器(如 Repeater)并调用 DataBind() 以获得 替换发生。
关于c# - 在 foreach 循环内设置用户控件的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1645293/