MVC应用中点击Refresh按钮时如何将JSON数据插入可展开HTML表格行
修复方案
1. 修正后端Refresh接口逻辑
原有接口存在语法错误、关联查询逻辑错误,修复后代码如下:
public async Task<JsonResult> Refresh() { try { // 预加载关联的Companies列表,无需单独循环赋值 var projectList = await _context.Project.Include(p => p.Companies).ToListAsync(); return Json(projectList); } catch (Exception ex) { throw ex; } }
如果你的EF版本不支持Include语法,也可以用原有循环逻辑修正:
public async Task<JsonResult> Refresh() { try { List<Project> projectList = _context.Project.ToList(); // 遍历每个Project赋值对应的Companies foreach(var item in projectList) { item.Companies = _context.Company.Where(x => x.CompanyId == item.CompanyId).ToList(); } // return要放在循环外 return Json(projectList); } catch (Exception ex) { throw ex; } }
2. 修正前端Refresh渲染逻辑
原有JS仅渲染了主行基础字段,没有拼接子行对应的Company字段单元格,且刷新DOM后需重新初始化Footable保证展开功能可用,修复后代码如下:
function refresh() { $.ajax({ type: "GET", url: '@Url.Action("Refresh", "Home")', dataType: "json", contentType: "application/json", success: function (response) { var trHTML = ''; $.each(response, function (i, item) { if (i < 15) { // 拼接主行基础字段 trHTML += '<tr class="footable-even"><td data-filter="#filter" class="footable-visible footable-first-column"><span class="footable-toggle"></span>' + item.Idx + '</td><td class="footable-visible">' + item.Project + '</td><td class="footable-visible">' + item.Name + '</td><td class="footable-visible">' + item.Phone + '</td><td class="footable-visible">' + item.Action + '</td><td class="footable-visible">' + item.CompanyId + '</td>'; // 拼接子行Company字段 $.each(item.Companies, function (idx, company) { trHTML += '<td>' + company.CompanyId + '</td>'; trHTML += '<td>' + company.CompanyName + '</td>'; trHTML += '<td>' + company.Completed + '</td>'; trHTML += '<td>' + company.Task + '</td>'; trHTML += '<td>' + company.Date + '</td>'; }); // 闭合行标签 trHTML += '</tr>'; } }); $('#projectModel tbody').html(trHTML); // 重新初始化Footable,恢复展开功能 $('#projectModel').footable(); }, error: function (error) { console.log(error); } }); }
3. 可选:修正视图层冗余代码
原有thead部分循环输出Company列会导致列重复,每个项目的Company列结构完全一致,无需循环,直接写死即可:
<thead> <tr> <th>Idx</th> <th>Project</th> <th>Name</th> <th>Phone</th> <th>Action</th> <th>CompanyId</th> <th data-hide="all">CompanyName</th> <th data-hide="all">Completed</th> <th data-hide="all">Task</th> <th data-hide="all">Date</th> </tr> </thead>
同时修正原有HTML标签错误:table的id属性缺少闭合引号,末尾div标签缺少闭合尖括号。
内容的提问来源于stack exchange,提问作者user12
相关产品推荐
相关产品推荐

