【问题标题】:ASP.NET how to populate html table on asp button clickASP.NET 如何在 asp 按钮单击时填充 html 表
【发布时间】:2014-06-06 00:22:24
【问题描述】:

我正在尝试使用基于 c# 函数在单击按钮时返回的内容填充行的 html 表。

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Populate" /></div><br>

<table id ="randtable" class="tablex">
  <tr>
    <th>Col1</th>
    <th>Col2</th>
    <th>Col3</th>
    <th>Col4</th>
  </tr>
</table>

我的 Button1_Click 函数如下所示:

protected void Button1_Click(object sender, EventArgs e)
{
    List<Entity> x = someFunction();
    //I want to have each row in the table represent each entity. Assume each entity has 4 attributes which would go in Col1,Col2,Col3,Col4 in the table.
}

知道怎么做吗?我坚持使用 html 表格而不是 asp 控制表格的原因是为了保留 html 表格的 css,除非有办法让 asp 表格看起来也很吸引人。

【问题讨论】:

  • 尝试众多 ASP.net 数据控件之一:GridView、ListView、Repeater。它们的设计考虑到了这一点。中继器是“最轻”的选项。 Gridview 可能是最重的。
  • ASP.net 控件有一个名为“CssClass”的属性,它与 HTML 控件的“类”相同..

标签: c# javascript jquery html asp.net


【解决方案1】:

将您的表格放在 ListView 控件中:

<asp:ListView runat=server id="lvResults">
  <LayoutTemplate>
    <table id ="randtable" class="tablex">
     <tr>
      <th>Col1</th>
      <th>Col2</th>
      <th>Col3</th>
      <th>Col4</th>
    </tr>
   <asp:PlaceHolder id="itemPlaceholder" runat="server"></asp:PlaceHolder>
  </table>
 </LayoutTemplate>
 <ItemTemplate>
  <tr>
   <td><%# Eval(Container.DataItem, "col1") %></td>
   <td><%# Eval(Container.DataItem, "col2") %></td>
   <td><%# Eval(Container.DataItem, "col3") %></td>
  </tr>
 </ItemTemplate>
</asp:ListView>

然后把下面的代码放在你的代码后面:

protected void Button1_Click(object sender, EventArgs e)
{
    List<Entity> x = someFunction();
    lvResults.DataSource = x;
    lvResults.DataBind()
}

【讨论】:

    【解决方案2】:

    如果您特别想在 html 表格上执行此操作,则可以在表格的 tbody 元素上使用 runat="server",然后在循环中填充表格的行。

    你的桌子是这样的:

     <table id ="randtable" class="tablex">   
      <thead>   
       <tr>
         <th>Col1</th>
         <th>Col2</th>   
       </tr> 
      </thead> 
      <tbody id="mybody" runat="server">
         //your dynamic rows from code behind
      </tbody> 
     </table>
    

    你的班级应该有这样的东西:

    protected void Button1_Click(object sender, EventArgs e) {
       List<Entity> x = someFunction();
       foreach (var entity in x)
           {
               mybody.InnerHtml += string.Format("<tr><td>{0}</td><td>{1}</td></tr>", 
                                                 entity.value1, entity.value2);
           }
    }
    

    【讨论】: