【问题标题】:How to provide 'data' to User Control inside repeater?如何向中继器内的用户控件提供“数据”?
【发布时间】:2011-09-26 02:23:57
【问题描述】:

有人可以解释向中继器内的用户控件提供数据的最简单方法吗?

我有以下几点:

默认.aspx

<!-- this.GetData() returns IEnumerable<Object> -->
<asp:Repeater runat="server" datasource='<%#this.GetData()%>'>
    <ItemTemplate>
        <my:CustomControl runat="server" datasource='<%#Container.DataItem %>
    </ItemTemplate>
</asp:Repeater>

代码隐藏

    protected void Page_Load(object sender, EventArgs e)
    {
        this.DataBind();
    }

CustomControl.ascx

<!-- Object has property Title -->
<h1><%#this.DataSource.Title%></h1>

代码隐藏:

[System.ComponentModel.DefaultBindingProperty("DataSource")]
public partial class CustomControl : System.Web.UI.UserControl
{
    public Item DataSource { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        var x = this.DataSource; //null here
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        var x = this.DataSource; //still null
    }
}

【问题讨论】:

  • this.GetData() 在发生数据绑定的 Page_Load 之前或之后被调用。您可以将.GetData() 移动到Page_Load 中的数据绑定之前吗?
  • this.GetData() 使用数据绑定表达式 # 调用。所以叫ON数据绑定...

标签: asp.net data-binding user-controls


【解决方案1】:

您可以向用户控件添加属性,然后在数据绑定期间设置这些属性。

像这样:

<!-- this.GetData() returns IEnumerable<Object> -->
<asp:Repeater runat="server" datasource='<%#this.GetData()%>'>
    <ItemTemplate>
        <my:CustomControl runat="server" title='<%#Container.DataItem.title %>
    </ItemTemplate>
</asp:Repeater>

代码隐藏

protected void Page_Load(object sender, EventArgs e)
{
    this.DataBind();
}

CustomControl.ascx

<!-- Object has property Title -->
<h1><%#this.Title%></h1>

代码隐藏:

[System.ComponentModel.DefaultBindingProperty("DataSource")]
public partial class CustomControl : System.Web.UI.UserControl
{
    public Item DataSource { get; set; }

    public string title { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        var x = this.DataSource; //null here
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        var x = this.DataSource; //still null
     }
}

【讨论】:

  • 上面略有不同,因为它不依赖于用户控件中的数据绑定,只依赖于页面数据绑定。我过去有 page.databind 没有传播到用户控件。我不能肯定地说,但我很确定情况就是这样。
【解决方案2】:

我在这里的另一篇文章中找到了一个优雅的解决方案: ASP.NET Loading a User Control in a Repeater 安东尼·佩格拉姆

总结:

使用中继器的 ItemDataBound(object sender, RepeaterItemEventArgs e) 事件将信息推送到 Web 用户控件的属性(您创建的)。

【讨论】:

    猜你喜欢
    • 2019-01-04
    • 2021-07-05
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2011-11-04
    相关资源
    最近更新 更多