加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何在转发器内为用户控件提供“数据”?

发布时间:2020-12-16 03:26:11 所属栏目:asp.Net 来源:网络整理
导读:有人可以解释向转发器内的用户控件提供数据的最简单方法吗? 我有以下内容: Default.aspx的 !-- this.GetData() returns IEnumerableObject --asp:Repeater runat="server" datasource='%#this.GetData()%' ItemTemplate my:CustomControl runat="server" d
有人可以解释向转发器内的用户控件提供数据的最简单方法吗?

我有以下内容:

Default.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() 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; //still null
     }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读