ASP.NET Core 数据库写入后在cshtml页面显示ViewBag列表异常
问题根因
你遇到的问题由3个错误共同导致:
- EF Core 查询时没有主动加载关联导航属性
- 前端非空判断逻辑写反了判断对象
- 所有年龄段标签的id属性重复,属于隐藏bug
修复步骤
1. 调整查询接口,添加关联数据加载
EF Core 默认不会自动加载导航属性,你需要用Include+ThenInclude手动加载联赛关联的中间表、以及中间表关联的参与者数据,同时补充缺失的性别筛选条件:
// 记得先引入命名空间 using Microsoft.EntityFrameworkCore; [HttpGet] [Route("roster/basketball")] public IActionResult BasketballRoster() { ViewBag.bbM7and8 = db.Leagues .Include(l => l.allParticipants) .ThenInclude(m => m.child) .Where(i=>i.sport == "Basketball" && i.ageRange == "7and8" && i.gender == "Male") .ToList(); // 其他年龄段的查询都按上面的格式修改,注意对应ageRange和gender参数 ViewBag.bbM9and10 = db.Leagues .Include(l => l.allParticipants) .ThenInclude(m => m.child) .Where(i=>i.sport == "Basketball" && i.ageRange == "9and10" && i.gender == "Male") .ToList(); // 剩下的年龄段以此类推修改即可 return View("RosterPageBasketball"); }
2. 修复前端判断逻辑
你之前的判断ViewBag.Any()是判断整个ViewBag对象是否有动态属性,不是判断bbM7and8列表是否有数据,改成以下写法:
<div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade" id="bbM7and8" role="tabpanel" aria-labelledby="bbM7and8-tab"> 7-8 @{ if(ViewBag.bbM7and8 != null && ViewBag.bbM7and8.Any()) { <p>the list is not empty</p> foreach(League j in ViewBag.bbM7and8) { if(j.allParticipants != null){ foreach(MMLeagueParticipant mmLp in j.allParticipants) { if(mmLp.child != null){ <p>@mmLp.child.ParticipantFirstName @mmLp.child.ParticipantLastName</p> } } } } } else { <p>the list is empty</p> } } </div> <!-- 其他年龄段标签修改id属性,避免重复,比如9-10的写法 --> <div class="tab-pane fade" id="bbM9and10" role="tabpanel" aria-labelledby="bbM9and10-tab"> <!-- 对应9-10年龄段的展示逻辑 --> </div> <div class="tab-pane fade" id="bbM11and12" role="tabpanel" aria-labelledby="bbM11and12-tab"> <!-- 对应11-12年龄段的展示逻辑 --> </div> <!-- 剩下的年龄段以此类推修改id即可 --> </div>
额外说明
你遇到的RuntimeBinderException是因为把遍历逻辑放到else分支时,触发了ViewBag.bbM7and8为null的场景,此时直接遍历空对象就会报运行时绑定错误,上面的修复已经规避了这个问题。
内容的提问来源于stack exchange,提问作者jgrewal
相关产品推荐
相关产品推荐

