简体   繁体   中英

How can i pass a c# variable in CommandName attribute in aspx page

How can i pass ac# variable in CommandName attribute in aspx page

I wanna pass the idCategory inside the CommandName attribute, when i try to do it with an html element like div or any it works, but with the asp.net element like asp:button doesn't. is there any way to solve that! and Thanks!


<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 %>

Use a repeater and bind it from code behind. Use CommandArgument instead of CommandName, if you are binding the category id.

aspx page

<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>

code behind

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);
}

Note: if you want to access Binding context in command handler, I suggest you to use OnItemCommand on repeater instead of OnCommand on button. You'll be able then to access current Item from event handler parameter: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM