c# - 如何在 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 %>
解决方案
使用中继器并从后面的代码中绑定它。如果要绑定类别 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。然后,您将能够从事件处理程序参数访问当前项目:
推荐阅读
- http - Indy 10 HTTPS 代理
- sql - PIVOT 多列不考虑聚合结果
- command-line - 由于权限更改导致的总线错误(核心转储)
- c# - 使用 { get; 将 .json 反序列化为 C# 放; } (牛顿软件)
- angular - 从 Angular 2 迁移到 Angular 4 后,模块“AppModule”导入错误意外值“t”。请添加@NgModule 注释
- mysql - 可以使用普通的 MySql jdbc 驱动程序写入 Mariadb。那为什么要使用单独的 MaraDB 驱动程序呢?
- c# - transform.forward 仅适用于 0,0,0 旋转,我想让它独立于旋转
- ansible - Ansible - 将字符串与变量组合以形成现有变量
- ios - 当用户稍后在 ios 11 中允许通知时使用推送通知
- selenium - 如何在 Selendroid 检查器中查看屏幕截图?