[英]How can i pass a c# variable in CommandName attribute in aspx page
我想在 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.