存储库代码:
public IQueryable<Bundle> getAllCustomBundlesByCompanyID(int companyID)
{
return from companyBundle in db.CompanyBundles
join bundle in db.Bundles on companyBundle.BundleID equals bundle.BundleID
where companyBundle.CompanyID == companyID && bundle.CompanyID == companyID
orderby bundle.BundleName ascending
select bundle;
}
Controller 代码:
ViewData["OurCategories"] = bundleRepository.getAllCustomBundlesByCompanyID(CompanyID);
查看代码:
<ul class="SmallCats">
<%if(ViewData["OurCategories"] != null){ %>
<%List<KODmvc.Models.Bundle> ourCategories = ViewData["OurCategories"] as List<KODmvc.Models.Bundle>; %>
<%foreach(KODmvc.Models.Bundle b in ourCategories) { %>
<li><a href="<%=b.BundleID%>">
<img src="/Content/images/bundleicons/<%=b.BundleIcon %>" />
<%=b.BundleName %></a>
</li>
<%} %>
<%} else { %>
There are no custom categories.
<%} %>
</ul>
错误:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 38: <%if(ViewData["OurCategories"] != null){ %>
Line 39: <%List<KODmvc.Models.Bundle> ourCategories = ViewData["OurCategories"] as List<KODmvc.Models.Bundle>; %>
Line 40: <%foreach(KODmvc.Models.Bundle b in ourCategories) { %>
Line 41: <li><a href="<%=b.BundleID%>">
Line 42: <img src="/Content/images/bundleicons/<%=b.BundleIcon %>" />
Source File: e:\Bancroft Archive\PanamaTrunk\Views\Asset\AdminDashboard.aspx Line: 40
但我正在检查以确保 ViewData 不为空,然后再让它进入,这到底是怎么回事??
请您参考如下方法:
好吧,如果 as 转换与您提供的类型不匹配,那么它会返回 null。您的 foreach 取消引用 ourCategories,此时它可能为 null。
如果您不打算显式测试 ourCategories 是否为 null,则应该使用 () 转换。然后,如果转换失败,您将收到一个有意义的错误。
