如何在ASP.NET WebForms中显示用户控件列表

5
这不是一个问题,所以我希望不会被解雇!我需要制作一个类似Twitter的时间轴,它是一堆包含信息的块叠加而成。
我真的不知道该怎么做。问题在于每次块的数量都不同,有时只有1个块,有时有两个或更多...
那么我要做一些HtmlWriter来直接编写html吗?我对asp.net还很陌生,也许可以更容易地完成这个任务!也许可以使用WebUserControl,一个块等于一个wuc,因此我可以添加所需的wuc数量... 我很迷茫,也许已经有人做过这样的事情并且可以指引我正确的方向...
谢谢阅读!
1个回答

10
你正在创建一个用户控件来表示“块”,这是正确的做法,但你缺少一种机制来将它们显示为列表。ASP.NET 有很多可能的解决方案,但最简单的方法是使用 ListView 控件。很难在不知道你的数据长什么样子的情况下提供示例代码,但我们假设你有一个名为 Block 的类:
public class Block
{
    public string Title {get; set;}
    public string Text { get; set; }
}
为了显示一个块,你需要创建一个用户控件,我们称之为BlockControl:
标记:
<div style="margin:10px; padding:10px; background:#eee;">
    <h2><%= Block.Title %></h2>
    <%= Block.Text %>
</div>

代码后台:

public partial class BlockControl : System.Web.UI.UserControl
{
    //Note the public property, we'll use this to data bind the ListView's item to the user control
    public Block Block { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

然后,在您的.aspx页面中,您可以声明一个ASP.NET ListView控件,并在ListView的ItemTemplate中使用BlockControl来呈现数据。请注意,我们将ListView的当前数据项绑定到BlockControl.Block属性。

<asp:ListView ID="BlockList" runat="server">
    <ItemTemplate>
        <uc:BlockControl Block="<%# Container.DataItem %>" runat="server" />
    </ItemTemplate>
</asp:ListView>            

在 .aspx 的后台代码中,您可以设置 ListView 数据源。在您的情况下,数据可能来自数据库,但这里只是一些模拟数据:

protected void Page_Load(object sender, EventArgs e)
{
    List<Block> blocks = new List<Block>
    {
        new Block { Title = "Block1", Text="This is the block 1 content"},
        new Block { Title = "Block2", Text="This is the block 2 content"}
    };

    this.BlockList.DataSource = blocks;
    this.BlockList.DataBind();
}

现在你有一个用户控件封装的单个块的演示,ListView提供了一种机制,可以根据你的数据显示可变数量的这些用户控件。


太棒了。谢谢! - Nash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接