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

ASP.NET 6 MVC Identity项目如何为用户列表添加邮箱搜索栏

实现方案(零JavaScript基础也能完成,基于ASP.NET Core MVC原生能力)

不需要写JavaScript也能实现基础的邮箱搜索过滤,走服务端表单提交逻辑即可,仅修改两处代码就能直接跑通,完全兼容你现有的Identity、EF Core技术栈:

第一步:修改Admin控制器的ListOfUsersAndRoles动作方法

给方法添加可选的搜索关键词参数,查询用户时直接在数据库层面做邮箱模糊匹配,不需要把全量用户拉到内存后再过滤,性能更好。修改后的代码如下:

public async Task<IActionResult> ListOfUsersAndRoles(string searchString)
{
    // 取用户集合的IQueryable对象,不立即执行数据库查询
    var usersQuery = _userManager.Users.AsQueryable();
    // 搜索参数非空时,追加邮箱不区分大小写的模糊匹配条件
    if (!string.IsNullOrWhiteSpace(searchString))
    {
        usersQuery = usersQuery.Where(u => u.Email.Contains(searchString));
    }
    // 执行查询,拿到过滤后的用户列表
    var users = await usersQuery.ToListAsync();
    
    var userRolesViewModel = new List<UserRolesViewModel>();
    foreach (ApplicationUser user in users)
    {
        var thisViewModel = new UserRolesViewModel();
        thisViewModel.UserId = user.Id;
        thisViewModel.Email = user.Email;
        thisViewModel.Name = user.UserName;
        thisViewModel.Roles = await GetUserRoles(user);
        userRolesViewModel.Add(thisViewModel);
    }
    // 把当前搜索关键词传到视图,用于搜索框内容回填
    ViewData["CurrentSearch"] = searchString;
    return View(userRolesViewModel);
}

说明:如果使用SQL Server作为数据库,Contains方法默认就会走不区分大小写的匹配,符合常规搜索的使用习惯。


第二步:修改ListOfUsersAndRoles视图,添加搜索表单

在页面标题和表格之间加一个GET提交的表单,不需要额外前端逻辑,输入关键词点搜索按钮就会触发请求,过滤后的结果直接返回页面渲染。修改后的视图代码如下:

<h1>List of users and roles</h1>

<!-- 搜索栏开始 -->
<form asp-action="ListOfUsersAndRoles" method="get" class="mb-3">
    <div class="input-group" style="max-width: 500px;">
        <input type="text" 
               name="searchString" 
               value="@ViewData["CurrentSearch"]" 
               class="form-control" 
               placeholder="输入用户邮箱关键词搜索">
        <button type="submit" class="btn btn-outline-primary">搜索</button>
        @if (!string.IsNullOrWhiteSpace(ViewData["CurrentSearch"]?.ToString()))
        {
            <a asp-action="ListOfUsersAndRoles" class="btn btn-outline-secondary">重置</a>
        }
    </div>
</form>
<!-- 搜索栏结束 -->

<table class="table">
    <thead>
        <tr>
            <th>Email</th>
            <th>Role</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var user in Model)
        {
        <tr>
            <td>@user.Email</td>
            <td>@string.Join(" , ", user.Roles.ToList())</td>
            <td>
                <a class="btn btn-primary" asp-controller="Admin" asp-action="ModifyRole" asp-route-userId="@user.UserId">Modify role</a>
            </td>
        </tr>
        }
    </tbody>
</table>

可选优化方向(掌握JS基础后再实现即可)

如果后续想要输入实时过滤、不用点击按钮刷新页面的体验,可以在熟悉JS基础后,加少量原生JS实现前端本地过滤,或者通过Ajax请求后端接口拉取过滤数据,当前先把上述服务端方案跑通即可,完全能满足基础使用需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:31:04