ASP.. NET如何在asp上填充html表按钮单击

本文关键字:html 填充 按钮 单击 asp NET ASP | 更新日期: 2023-09-27 18:07:17

我试图根据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如何在asp上填充html表按钮单击

把你的表放到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()
}

如果你特别想在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);
       }
}