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

.NET Core Razor实现仅搜索时显示表格行的方法问询

实现默认隐藏表格行,仅搜索时展示匹配行的方案

方案一:前端本地过滤(适合数据量较小的场景)

基于你现有代码,通过前端JS控制行的显示隐藏,无需修改后端逻辑:

  1. 修改表格行的Razor代码:给每个<tr>添加统一类名,并默认隐藏
<style>
/* 默认隐藏所有患者行 */
.patient-row {
    display: none;
}
</style>

<!-- 新增搜索区域 -->
<div class="mb-3">
    <input type="text" id="searchInput" placeholder="输入患者姓名/电话/病症搜索..." class="form-control">
    <button id="searchBtn" class="btn btn-primary mt-2">搜索</button>
</div>

<table>
    <thead>
        <!-- 此处保留你的表头代码 -->
    </thead>
    <tbody id="tblBody">
    @{
        foreach (var item in Model.Patients)
        {
                <tr id="row_@item.Id" class="patient-row">

                    <td id="patientName_@item.Id" class="table-cell-arabic">@item.PatientName</td>
                    <td id="phone_@item.Id">@item.Phone</td>
                    <td id="Diseases_@item.Id">@item.Diseases</td>
                    <td>
                        <button class="btn btn-danger btn-xs sm-btn-table" type="button" onclick="OnDelete(@item.Id)">Delete</button>
                        <button class="btn btn-success btn-xs sm-btn-table" type="button" onclick="OnEdit(@item.Id)">Edit</button>
                        <button class="btn btn-success btn-xs sm-btn-table" type="button" onclick="OnDetails(@item.Id)">Details</button>

                    </td>
                </tr>
            
        }
    }
    </tbody>
</table>
  1. 添加搜索逻辑的JavaScript
<script>
document.getElementById('searchBtn').addEventListener('click', function() {
    performSearch();
});

// 支持回车触发搜索
document.getElementById('searchInput').addEventListener('keyup', function(e) {
    if (e.key === 'Enter') {
        performSearch();
    }
});

function performSearch() {
    const keyword = document.getElementById('searchInput').value.trim().toLowerCase();
    const rows = document.querySelectorAll('.patient-row');

    rows.forEach(row => {
        // 获取行内关键文本内容
        const name = row.querySelector('[id^="patientName_"]').textContent.toLowerCase();
        const phone = row.querySelector('[id^="phone_"]').textContent.toLowerCase();
        const disease = row.querySelector('[id^="Diseases_"]').textContent.toLowerCase();

        // 判断是否匹配关键词,控制行的显示/隐藏
        if (name.includes(keyword) || phone.includes(keyword) || disease.includes(keyword)) {
            row.style.display = 'table-row';
        } else {
            row.style.display = 'none';
        }
    });
}
</script>

方案二:后端AJAX异步加载(适合数据量较大的场景)

初始不加载任何数据,仅在搜索时请求后端获取匹配结果,避免一次性加载大量数据:

  1. 修改Razor页面初始状态
<div class="mb-3">
    <input type="text" id="searchInput" placeholder="输入患者姓名/电话/病症搜索..." class="form-control">
    <button id="searchBtn" class="btn btn-primary mt-2">搜索</button>
</div>

<table>
    <thead>
        <!-- 此处保留你的表头代码 -->
    </thead>
    <tbody id="tblBody">
        <!-- 初始为空,搜索后动态渲染内容 -->
    </tbody>
</table>
  1. 添加后端API接口
    在你的Controller中新增处理搜索请求的Action:
[HttpGet]
public IActionResult SearchPatients(string keyword)
{
    // 根据关键词查询数据库中的患者数据
    var matchedPatients = _dbContext.Patients
        .Where(p => p.PatientName.Contains(keyword) 
                 || p.Phone.Contains(keyword) 
                 || p.Diseases.Contains(keyword))
        .ToList();
    
    return Json(matchedPatients);
}
  1. 添加前端AJAX搜索逻辑
<script>
document.getElementById('searchBtn').addEventListener('click', function() {
    performSearch();
});

document.getElementById('searchInput').addEventListener('keyup', function(e) {
    if (e.key === 'Enter') {
        performSearch();
    }
});

function performSearch() {
    const keyword = document.getElementById('searchInput').value.trim();
    const tbody = document.getElementById('tblBody');

    if (!keyword) {
        tbody.innerHTML = ''; // 关键词为空时清空表格
        return;
    }

    // 发送AJAX请求到后端接口
    fetch(`/YourControllerName/SearchPatients?keyword=${encodeURIComponent(keyword)}`)
        .then(response => response.json())
        .then(patients => {
            // 清空现有行
            tbody.innerHTML = '';
            
            // 动态渲染匹配的患者行
            patients.forEach(item => {
                const row = document.createElement('tr');
                row.id = `row_${item.Id}`;
                
                row.innerHTML = `
                    <td id="patientName_${item.Id}" class="table-cell-arabic">${item.PatientName}</td>
                    <td id="phone_${item.Id}">${item.Phone}</td>
                    <td id="Diseases_${item.Id}">${item.Diseases}</td>
                    <td>
                        <button class="btn btn-danger btn-xs sm-btn-table" type="button" onclick="OnDelete(${item.Id})">Delete</button>
                        <button class="btn btn-success btn-xs sm-btn-table" type="button" onclick="OnEdit(${item.Id})">Edit</button>
                        <button class="btn btn-success btn-xs sm-btn-table" type="button" onclick="OnDetails(${item.Id})">Details</button>
                    </td>
                `;
                
                tbody.appendChild(row);
            });
        })
        .catch(error => console.error('搜索出错:', error));
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:05:22