将报表表格移至首页时出现“Object reference not set...”错误求助
问题描述
原本Index页面有按钮跳转至Reports.cshtml视图(内含硬件报表表格),现在希望移除按钮,直接在Index页面展示该表格,但粘贴表格代码后触发异常。
核心问题原因
Index页面对应的Home控制器Index方法未给ViewModel的Report_HardwareListByExpiration属性赋值——Reports视图能正常运行,是因为ReportsController的Reports方法初始化了该属性并填充了数据。直接将依赖该属性的表格代码移到Index页面后,Model.Report_HardwareListByExpiration会是null,调用FirstOrDefault()或遍历集合时就会抛出空引用异常。
解决方案
1. 给Index页面的ViewModel填充报表数据
修改Home控制器的Index方法,添加和Reports控制器一致的报表数据初始化逻辑:
public class HomeController : Controller { public ActionResult Index() { // 登录校验(和Reports控制器逻辑保持一致) if (Session["UserID"] == null || !(bool)Session["IsLoggedIn"]) { return RedirectToAction("Login", "Account"); } // 初始化ViewModel并填充硬件报表数据 ViewModel myViewModel = new ViewModel { User = GetSessionInfoFromSessions(), // 若该方法是Reports控制器私有方法,需提取到公共工具类/基类中 Params = new ParametersModel { Start_Date = new DateTime(2015, 12, 31), End_Date = DateTime.Now.AddDays(60) } }; myViewModel.Report_HardwareListByExpiration = InvHardwareModel.Report_HardwareListByExpiration(myViewModel); return View(myViewModel); } }
2. 优化视图代码的空值防护
为避免后续空引用问题,在视图中添加空值校验,即使数据为空也不会报错:
<table id="hardware-data-table" class="table table-striped table-hover"> <thead bgcolor="silver"> <tr> <th hidden="hidden"> @Html.LabelFor(model => model.Report_HardwareListByExpiration?.FirstOrDefault()?.InvHardwareID) </th> <th> @Html.LabelFor(model => model.Report_HardwareListByExpiration?.FirstOrDefault()?.Equipment) </th> <th> @Html.LabelFor(model => model.Report_HardwareListByExpiration?.FirstOrDefault()?.HardwareModel) </th> <th> @Html.LabelFor(model => model.Report_HardwareListByExpiration?.FirstOrDefault()?.WL_EndDateFormatted) </th> </tr> </thead> <tbody> @if (Model.Report_HardwareListByExpiration != null) { foreach (var item in Model.Report_HardwareListByExpiration) { if (item.WL_EndDate < DateTime.Now && item.WL_EndDate > DateTime.Now.AddYears(-99)) { <tr> <td hidden="hidden">@item.InvHardwareID</td> <td>@item.Equipment</td> <td>@item.HardwareModel</td> <td style="background-color: #ff726f">@item.WL_EndDateFormatted</td> </tr> } if (item.WL_EndDate > DateTime.Now && item.WL_EndDate < DateTime.Now.AddYears(99)) { <tr> <td hidden="hidden">@item.InvHardwareID</td> <td>@item.Equipment</td> <td>@item.HardwareModel</td> <td style="background-color: orange">@item.WL_EndDateFormatted</td> </tr> } } } else { <tr> <td colspan="4" class="text-center">暂无数据</td> </tr> } </tbody> </table>
这里使用空传播运算符?.避免空集合调用FirstOrDefault()的异常,同时在遍历前判断集合是否为null。
3. 确认Index视图的模型类型
确保Index.cshtml顶部声明了正确的模型类型,与Reports视图一致:
@model YourNamespace.ViewModel
将YourNamespace替换为项目中ViewModel所在的实际命名空间。
内容的提问来源于stack exchange,提问作者Acadia
相关产品推荐
相关产品推荐

