首页 > 解决方案 > 如何在 aspx 页面的 CommandName 属性中传递 ac# 变量

问题描述

如何在 aspx 页面的 CommandName 属性中传递 ac# 变量

我想在 CommandName 属性中传递 idCategory,当我尝试使用 div 之类的 html 元素或任何它可以使用的元素时,但使用 asp:button 之类的 asp.net 元素却没有。有什么办法可以解决!谢谢!


<tbody ID="tbody">
<% 
   DAL.InventoryEntities Ie = new DAL.InventoryEntities();
   foreach (DAL.Category category in Ie.Categories) { 
%>

  <tr>
    <td><%: category.idCategory %></td>
    <td><%: category.name %></td>
    <td>
      <asp:LinkButton runat="server" 
                      CommandName='<%= category.idCategory %>'
                      CssClass="btn btn-info btn-block btn-md" 
                      Text="Select" 
                      OnCommand="Select_Command"></asp:LinkButton>
      </td>
  </tr>

<% } %>
</tbody>

> code behind:

protected void Select_Command(object sender, CommandEventArgs e)
{
    Response.Write("Hello " + e.CommandName);
}

output: Hello <%= category.idCategory %>

标签: c#asp.net.netvariables

解决方案


使用中继器并从后面的代码中绑定它。如果要绑定类别 ID,请使用 CommandArgument 而不是 CommandName。

页面

<table>
    <asp:Repeater ID="rpt" runat="server" OnInit="rpt_Init" ItemType="DAL.Category">
        <ItemTemplate>
            <tr>
                <td>
                    <tr>
                        <td><%# Item.idCategory %></td>
                        <td><%# Item.name %></td>
                        <td>
                            <asp:LinkButton runat="server"
                                CommandArgument="<%# Item.idCategory %>"
                                CssClass="btn btn-info btn-block btn-md"
                                Text="Select"
                                OnCommand="Select_Command"></asp:LinkButton>
                        </td>
                    </tr>
                </td>
            </tr>
        </ItemTemplate>
    </asp:Repeater>
</table>

后面的代码

protected void rpt_Init(object sender, EventArgs e)
{
   DAL.InventoryEntities Ie = new DAL.InventoryEntities();
   rpt.DataSource = Ie.Categories;
   rpt.DataBind();
}

protected void Select_Command(object sender, CommandEventArgs e)
{
   Response.Write("Hello " + e.CommandArgument);
}

注意:如果您想在命令处理程序中访问绑定上下文,我建议您在中继器上使用 OnItemCommand 而不是按钮上的 OnCommand。然后,您将能够从事件处理程序参数访问当前项目: 在此处输入图像描述


推荐阅读