使用foreach循环根据数据库中的记录数动态生成HTML元素

时间:2016-12-29 10:40:02

标签: c# html linq

Unitime.aspx

<asp:Content ID="Content2" ContentPlaceHolderID="cph2" Runat="Server">
   <div id="userPost" style="width:560px">
     <div id="firstPart">
        <div class="firstLeft">
            <asp:Image ID="imgProfile" runat="server" Height="50px"         ImageUrl="~/Images/ProfilePic/andre.jpg" Width="50px" />
        </div>
        <div class="firstRight">
            <asp:ImageButton ID="imgbtnRemove" runat="server" Height="15px" Width="15px" ImageUrl="~/Images/Icons/wrong.png" />
        </div>
        <div class="firstCenter">
            <asp:Label ID="lblUsername" runat="server" Text="Label"></asp:Label>
            <br /><asp:Label ID="lblTime" runat="server" Text="Label"></asp:Label>
        </div>

    </div>

    <div id="secondPart">
        <asp:Label ID="lblDescription" runat="server" Text="Label"></asp:Label>
        </div>

    <div id="thirdPart">
        <asp:Image ID="imgPost" runat="server" Height="357px" Width="476px" />
        <br />
    </div>

    <div id="fourthPart">
        By:<asp:Label ID="lblSociety" runat="server" Text="Label"></asp:Label>
    </div>
</div>
</asp:Content>

unitime.aspx.cs

public partial class ActivityBoard : System.Web.UI.Page
{
    WooooDataContext db = new WooooDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            foreach(UniTime u in db.UniTimes)
            {
                lblSociety.Text = u.society;

                var time = u.timeCreated;
                lblTime.Text = time.ToString();
                lblTime.Text = timeAgo.relativeTime(u.timeCreated);

                var studentid = u.studentID;
                var un = from n in db.Students
                         where n.studentID == studentid
                         select new
                         {
                             n.username,
                             n.profilePic
                         };

                foreach (var x in un)
                {
                    string xx = x.username.ToString();
                    lblUsername.Text = xx;
                    string profile = x.profilePic.ToString();
                    imgProfile.ImageUrl = string.Concat("Images/ProfilePic/", profile);
                }


                imgPost.ImageUrl = string.Concat("Images/UniTime/", u.photoURL);
                lblDescription.Text = u.description;
            }
        }
    }

我正在构建类似facebook的模型。所以我想从数据库中检索相关数据并插入到这个HTML元素中以显示它。但现在我面临的问题是我只能显示其中一条记录。我想要做的是使用foreach循环来循环用户&#39;根据我在数据库中记录的数量发布帖子。无论如何,我可以将HTML代码添加到C#文件的foreach循环中以实现所需的效果吗?谢谢。 enter image description here

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。基本上你需要包装你的&#34; userPost&#34;转发器中的div类似于&#34;列表视图&#34;。 &#34; userPost&#34;将是listview中的itemTemplate。 看看这个enter link description here