You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET:如何在ListView的<li>中触发OnCommand传递参数至后台

解决方案

方案1:使用LinkButton包裹列表项(推荐)

直接用<asp:LinkButton>包裹<li>内部所有内容,利用LinkButton的服务器端事件实现需求,既能保留原有HTML结构,又能正常传递参数:

<asp:ListView ID="CategoryList" runat="server">
   <ItemTemplate>
      <ul id="container">
         <li>
            <asp:LinkButton ID="lnkCategory" runat="server" 
                OnCommand="btnMoreInfo_Command" 
                CommandArgument='<%# Eval("CategorieNaam") %>'
                CssClass="li-link">
                <img src='<%# Eval("CategorieAfbeelding") %>' alt="">
                <p><%# Eval("CategorieNaam") %></p>
            </asp:LinkButton>
         </li>
      </ul>
   </ItemTemplate>
</asp:ListView>

添加CSS去除LinkButton默认链接样式,让它和普通列表项外观一致:

.li-link {
    text-decoration: none;
    color: inherit;
    display: block;
    cursor: pointer;
}

后台代码沿用你原本的btnMoreInfo_Command逻辑即可:

protected void btnMoreInfo_Command(object sender, CommandEventArgs e)
{
    string categorieNaam = e.CommandArgument.ToString();
    // 编写你的业务逻辑
}

方案2:通过JavaScript触发回传

如果不想用服务器控件包裹,给<li>添加点击事件,调用ASP.NET内置的__doPostBack方法传递参数:

<asp:ListView ID="CategoryList" runat="server">
   <ItemTemplate>
      <ul id="container">
         <li onclick='__doPostBack("CategoryList", "<%# Eval("CategorieNaam") %>")'>
            <img src='<%# Eval("CategorieAfbeelding") %>' alt="">
            <p><%# Eval("CategorieNaam") %></p>
         </li>
      </ul>
   </ItemTemplate>
</asp:ListView>

在后台Page_Load事件中处理回传参数:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        string target = Request.Form["__EVENTTARGET"];
        string argument = Request.Form["__EVENTARGUMENT"];
        
        if (target == "CategoryList" && !string.IsNullOrEmpty(argument))
        {
            string categorieNaam = argument;
            // 编写你的业务逻辑
        }
    }
}

方案1简洁无需额外JS逻辑,方案2更灵活适合自定义前端交互场景,按需选择即可。

内容的提问来源于stack exchange,提问作者Siebie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:03:27