ASP.NET MVC 5使用foreach填充表格出现空<td>列填充异常问题
核心问题说明
你代码中所有<td>单元格标签未正确闭合,结束位置错误写成了<td>而非</td>,浏览器解析时会自动补全缺失的闭合标签,同时会把你写错的起始<td>识别为新的空单元格,最终每行就会生成4个单元格,导致第二列数据错位、出现多余空<td>。
修正后的Index.cshtml代码
@model IEnumerable<Vidly.Models.Customer> @{ ViewBag.Title = "Customers"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>@ViewBag.Title</h2> <div class="table-responsive"> <table id="customers" class="table table-bordered table-hover"> <thead> <tr> <th>Customer</th> <th>Discount Rate</th> </tr> </thead> <tbody> @foreach (var customer in Model) { <tr> <td>@Html.ActionLink(customer.Name, "Details", "Customers", new {id = customer.Id}, new {@class = ""})</td> <!-- 增加空值判断,避免MembershipTypes为null时报错 --> <td>@(customer.MembershipTypes?.DiscountRate ?? "0")</td> </tr> } </tbody> </table> </div> <!-- 原有删除空行的JS已不需要,标签修正后不会再生成无效空行 -->
额外注意点
- 如果你的项目C#版本不支持空条件运算符
?.,可以换成传统判断写法:
<td>@(customer.MembershipTypes != null ? customer.MembershipTypes.DiscountRate.ToString() : "0")</td>
- 确认你的Customer模型中MembershipTypes导航属性已正确配置,查询数据时已通过Include预加载该关联属性,避免出现懒加载异常或者属性为null的情况。
内容的提问来源于stack exchange,提问作者user2529011
相关产品推荐
相关产品推荐

