簡體   English   中英

如何在 aspx 頁面的 CommandName 屬性中傳遞 ac# 變量

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

如何在 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 %>

使用轉發器並從后面的代碼綁定它。 如果要綁定類別 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。 然后,您將能夠從事件處理程序參數訪問當前項目: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM