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

ASP.NET Core MVC:如何将表格选中行转为全局可用变量

在ASP.NET Core MVC中实现表格行选中并获取详情

1. 修改前端表格的点击事件

更新你的cshtml代码,给表格行添加点击事件并传递当前行的NAME值:

<div class="menu">
    <table id="table-resumida" class="table">
        <thead>
            <tr>
                <th scope="col">Seq.</th>
                <th scope="col">Nome</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr style="cursor: pointer" onclick="handleRowClick(@Html.Raw(Json.Serialize(item.NAME)))">
                    <td>
                        @item.SEQ
                    </td>
                    <td>
                        @item.NAME
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

这里用@Html.Raw(Json.Serialize(item.NAME))确保字符串参数安全传递,避免引号或特殊字符导致语法错误。

2. 编写JavaScript处理函数

在页面底部添加script标签,实现点击后的逻辑:保存选中的NAME值、高亮选中行、调用后端接口获取详情并填充页面:

<script>
// 全局变量存储选中的NAME值,供其他函数调用
let selectedName = '';

function handleRowClick(name) {
    // 保存选中的NAME
    selectedName = name;
    
    // 高亮选中行,移除其他行的高亮
    document.querySelectorAll('#table-resumida tbody tr').forEach(row => {
        row.classList.remove('table-active');
    });
    event.currentTarget.classList.add('table-active');
    
    // 调用后端接口获取详细信息
    fetch(`/Person/GetDetailsByName?name=${encodeURIComponent(name)}`)
        .then(response => {
            if (!response.ok) throw new Error('请求失败');
            return response.json();
        })
        .then(data => {
            // 填充页面上的详情字段(根据实际HTML结构调整ID)
            document.getElementById('lastName').textContent = data.LAST_NAME;
            document.getElementById('age').textContent = data.AGE;
            document.getElementById('height').textContent = data.HEIGHT;
        })
        .catch(error => console.error('获取详情出错:', error));
}

// 示例:其他需要使用selectedName的函数
function doSomethingWithSelectedName() {
    if (selectedName) {
        console.log('当前选中的姓名:', selectedName);
        // 此处可添加额外业务逻辑,比如执行自定义查询等
    }
}
</script>

3. 后端接口实现

在对应的Controller中添加接口,根据NAME查询完整信息:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

public class PersonController : Controller
{
    private readonly YourDbContext _context;

    public PersonController(YourDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IActionResult GetDetailsByName(string name)
    {
        var person = _context.People
            .FirstOrDefault(p => p.NAME == name);
        
        if (person == null)
        {
            return NotFound("未找到对应记录");
        }
        
        return Json(person);
    }
}

注意替换YourDbContext为你实际的数据库上下文类,People为对应的DbSet名称。

4. 添加详情展示区域

在视图中添加用于显示详细信息的HTML元素:

<div class="details-container mt-4">
    <h3>详细信息</h3>
    <div class="card">
        <div class="card-body">
            <p><strong>姓氏:</strong> <span id="lastName">-</span></p>
            <p><strong>年龄:</strong> <span id="age">-</span></p>
            <p><strong>身高:</strong> <span id="height">-</span></p>
        </div>
    </div>
</div>

关键说明

  • selectedName是全局变量,可在任意需要的函数中直接调用。
  • 使用encodeURIComponent处理NAME参数,避免特殊字符导致URL解析错误。
  • 高亮行使用Bootstrap的table-active类,未使用Bootstrap可自定义CSS样式替代。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:00:39