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

点击表格行后向View Component传递参数的实现方案

问题

在常规View中,我们通过模型渲染表格,代码如下:

@foreach (var item in Model)
{
   if (item.PartnerSubscriptionID > 0)
   {
     <tr id='customlistid_@item.CustomList.ListID'>
       <td>
        <button type="button" class="btn btn-secondary" onclick='ListCustomEdit("@item.CustomList.ListID")'>
         <i class='fas fa-users'></i>
        </button>                                    
      </td>
       <td style="display:none">@Html.DisplayFor(modelItem => item.CustomList.ListID)</td>
       <td style="text-align:left">@Html.DisplayFor(modelItem => item.CustomList.ListName)</td>
       <td><button id='btnDelete' type='button' class='btn btn-danger' onclick='ListCustomDeleteConfirm(" @item.CustomList.ListID ")'><i class='fas fa-trash'></i></button></td>
      </tr>
    }
}

同一页面中存在一个View Component,当硬编码ListID(如ListID=7)时可正常运行,代码如下:

<div class="col-8">
 @await Component.InvokeAsync("ListCustomMembers" ,  new {ListID = 7 } )
</div>

现在需要在用户点击表格行(或当前绑定onclick事件的按钮)时,将对应的ListID传入并刷新该View Component,请问该如何实现?

解决方案

步骤1:给View Component容器添加唯一标识

先修改渲染View Component的div,增加专属id,方便后续通过JS定位替换内容:

<div id="customMembersContainer" class="col-8">
 @await Component.InvokeAsync("ListCustomMembers", new { ListID = 7 })
</div>

步骤2:修改点击事件绑定

可以直接复用现有按钮的点击事件,或者给表格行绑定点击逻辑,核心是传递目标ListID:
比如修改编辑按钮的onclick属性:

<button type="button" class="btn btn-secondary" onclick='loadCustomMembers("@item.CustomList.ListID")'>
 <i class='fas fa-users'></i>
</button>

如果要绑定表格行点击:

<tr id='customlistid_@item.CustomList.ListID' onclick='loadCustomMembers("@item.CustomList.ListID")'>

步骤3:编写JS异步刷新逻辑

在页面底部添加JavaScript函数,通过AJAX请求获取View Component的最新渲染内容,替换容器内的HTML:

function loadCustomMembers(listId) {
    fetch(`/Home/LoadListCustomMembers?listId=${listId}`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('customMembersContainer').innerHTML = html;
        })
        .catch(error => console.error('加载成员列表失败:', error));
}

如果项目中使用jQuery,也可以用更简洁的写法:

function loadCustomMembers(listId) {
    $.get(`/Home/LoadListCustomMembers?listId=${listId}`, function(html) {
        $('#customMembersContainer').html(html);
    });
}

步骤4:在Controller中添加View Component的请求端点

需要在对应Controller里新增一个Action,负责调用View Component并返回渲染后的HTML:

public IActionResult LoadListCustomMembers(int listId)
{
    // 可在此处添加listId合法性校验逻辑
    return ViewComponent("ListCustomMembers", new { ListID = listId });
}

额外提示

  • 可以在请求发起时给customMembersContainer添加加载动画,提升用户体验
  • 务必在Controller的Action中校验listId的有效性,避免非法请求导致的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:45:32