【问题标题】:How can i pass a c# variable in CommandName attribute in aspx page如何在 aspx 页面的 CommandName 属性中传递 c# 变量
【发布时间】:2020-02-28 11:25:52
【问题描述】:

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

当我尝试这样做时,我想在 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 %>

【问题讨论】:

  • 尝试在CommandName='&lt;%= category.idCategory %&gt;'中将=替换为#
  • > 编译错误 ​​ton>

标签: c# asp.net .net variables


【解决方案1】:

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

aspx 页面

<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。然后,您将能够从事件处理程序参数访问当前项目:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 2011-09-23
    • 1970-01-01
    • 2015-06-02
    相关资源
    最近更新 更多