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

MVC 5中点击首表格行时如何动态加载第二表格的关联数据

解决方案

核心逻辑是将后端已经预加载完成的学生关联课程数据,提前序列化为前端可直接读取的JS对象,通过原生DOM事件绑定实现本地数据切换,全程不需要额外发起AJAX请求。


完整实现代码

直接修改你的Razor视图代码即可:

@model IEnumerable<Students>
@{
    // 预先格式化所有学生的课程数据,转为JSON供前端调用
    var studentCourseMap = Model.Select(s => new
    {
        StudentId = s.id,
        CourseList = s.StudentClasses.Select(sc => sc.ClassName).ToList()
    });
    // 序列化JSON,根据项目依赖选择对应序列化库即可
    var courseMapJson = Newtonsoft.Json.JsonConvert.SerializeObject(studentCourseMap);
    // 若项目用System.Text.Json则替换为:
    // var courseMapJson = System.Text.Json.JsonSerializer.Serialize(studentCourseMap);
}

<!-- 布局样式:实现两个表格并排展示 -->
<style>
    .table-group {
        display: flex;
        gap: 3rem;
        align-items: flex-start;
    }
    .student-item {
        cursor: pointer;
    }
    .student-item:hover {
        background: #f0f0f0;
    }
    table {
        border-collapse: collapse;
    }
    td,th {
        border: 1px solid #ccc;
        padding: 8px 12px;
    }
</style>

<div class="table-group">
    <!-- 第一个表格:学生列表 -->
    <div>
        <h4>Table 1</h4>
        <table>
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var stu in Model)
                {
                    <tr class="student-item" data-stu-id="@stu.id">
                        <td>@stu.Name</td>
                        <td>@stu.Age</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>

    <!-- 第二个表格:课程展示 -->
    <div>
        <h4>Table 2</h4>
        <table id="courseTable">
            <tbody>
                <tr>
                    <td style="width:300px">请点击左侧学生查看对应课程</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

<script>
    // 读取后端注入的全量学生课程数据
    const allCourseData = @Html.Raw(courseMapJson);

    // 绑定学生行点击事件
    document.querySelectorAll('.student-item').forEach(row => {
        row.addEventListener('click', function () {
            // 取当前点击学生的ID
            const currentStuId = parseInt(this.dataset.stuId);
            // 匹配对应学生的课程列表
            const currentCourses = allCourseData.find(item => item.StudentId === currentStuId)?.CourseList || [];
            // 更新第二个表格内容
            document.querySelector('#courseTable tbody').innerHTML = `<tr><td>${currentCourses.join(' ')}</td></tr>`;
        })
    })
</script>

补充说明

该方案完全复用了你已经懒加载完成的关联数据,所有数据在页面首次渲染时就已经全部加载到前端,点击学生时仅做本地数据匹配和DOM更新,没有任何额外的后端请求,完全符合你的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:30:04