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

如何在增删DataTables行时无需刷新页面更新UI?

问题描述

我在cshtml文件中使用DataTables渲染了一个用户表格,通过select2组件添加用户,点击表格行内按钮可删除指定用户。目前增删功能均可正常运行,但每次操作后都需要刷新页面才能显示变更。请问是否有简单的方法实现增删行后无需刷新页面即可更新UI?是否需要使用AJAX?

相关代码

后端控制器代码

[Authorize(Policy = CMPConstants.AdminUsersOnly)]
public IActionResult GroupDetails(string groupName)
{ 
    // 返回数据模型用于cshtml渲染
    var trustMarqueAdmin = SetWrapperModel(groupName);
    return this.View(trustMarqueAdmin);
}

[Authorize(Policy = CMPConstants.AdminUsersOnly)]
public async Task RemoveFromGroup(string? userId, string? groupId)
{
    await this.b2cRepository.DeleteUserFromGroup(userId, groupId).ConfigureAwait(false);
}

[Authorize(Policy = CMPConstants.AdminUsersOnly)]
public async Task<IActionResult> AddToGroup(string groupId, string?[] userIdList, string groupName)
{
    await this.b2cRepository.AddUserToGroup(groupId, userIdList, groupName).ConfigureAwait(false);
    // 返回新增的用户数据,用于前端更新UI
    var newUsers = await this.b2cRepository.GetUsersByIds(userIdList).ConfigureAwait(false);
    return Json(newUsers);
}

前端CSHTML表格代码

<table id="admin-users-table" class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.TMUser.DisplayName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TMUser.GivenName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TMUser.Surname)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TMUser.CompanyName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TMUser.AccessLevel)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TMUser.AccessScope)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.TMUser.PrismUser)
            </th>
            <th>
                Remove
            </th>
        </tr>
    </thead>
    <tbody id="table-body-admin-users">
        @foreach (var member in Model.CurrentGroupMembers)
        {
            <tr data-user-id="@member.Id">
                <td>
                    @Html.DisplayFor(modelItem => member.DisplayName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => member.GivenName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => member.Surname)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => member.CompanyName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => member.AccessLevel)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => member.AccessScope)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => member.PrismUser)
                </td>
                <td>
                    <button type="button" class="btn btn-secondary delete-user-icon" onclick="RemoveFromGroup('@member.Id','@Model.TMGroup.Id','@member.GivenName','@member.Surname', '@Model.GroupName')">remove</button>
                </td>
            </tr>
        }
    </tbody>
</table>

前端JavaScript代码

// 初始化DataTables并保存实例,方便后续操作
let userTable;
$(document).ready(function () {
  userTable = $('#admin-users-table').DataTable({
     allowClear: true,
   });
 });

// 添加用户到组
function AddToGroup(groupId, groupName) {
  $("#confirm-add-group").modal('show');
  
  // 绑定确认按钮事件,先解绑避免重复绑定
  $("#confirm-add-btn").off('click').on('click', function() {
    $.post('/Home/AddToGroup', 
         { 
          userIdList: userIds, 
          groupId: groupId, 
          groupName: groupName 
      })
      .done(function(newUsers) {
          $("#confirm-add-group").modal('hide');
          // 遍历新增用户,插入表格
          newUsers.forEach(user => {
              const newRow = userTable.row.add([
                  user.DisplayName,
                  user.GivenName,
                  user.Surname,
                  user.CompanyName,
                  user.AccessLevel,
                  user.AccessScope,
                  user.PrismUser,
                  `<button type="button" class="btn btn-secondary delete-user-icon" onclick="RemoveFromGroup('${user.Id}','${groupId}','${user.GivenName}','${user.Surname}', '${groupName}')">remove</button>`
              ]).draw(false);
              // 给新行添加用户ID标识
              newRow.node().setAttribute('data-user-id', user.Id);
          });
      })
      .fail(function() {
          alert('添加用户失败,请重试');
      });
  });
}

// 从组中移除用户
function RemoveFromGroup(userId, groupId, fName, lName, groupName) {
  $(".confirm-delete").off('click').on('click', function () {
   $.post('/Home/RemoveFromGroup', { userId: userId, groupId: groupId })
    .done(function() {
        $(".confirm-delete-modal").modal('hide');
        // 通过用户ID定位行并删除,保持分页位置不变
        userTable.row(`tr[data-user-id="${userId}"]`).remove().draw(false);
    })
    .fail(function() {
        alert('删除用户失败,请重试');
    });
  });
}
关键说明
  1. 必须使用AJAX:你当前代码已经在用$.post(属于AJAX),但缺少操作成功后的UI更新逻辑,这是需要刷新页面的核心原因。
  2. DataTables实例复用:初始化时保存表格实例,方便后续调用官方API直接操作表格行。
  3. 删除操作优化:给表格行添加data-user-id属性,精准定位要删除的行,调用row().remove().draw(false)更新UI(draw(false)保留当前分页位置)。
  4. 添加操作优化:修改后端AddToGroup方法返回新增用户数据,前端在AJAX成功回调中用row.add()插入新行,再更新表格。
  5. 事件绑定优化:用off('click').on('click')避免重复绑定事件,防止多次点击触发重复请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:50:20