在Asp.net MVC4中访问ViewBag时出现了NullReferenceException异常。

7
我正在尝试在视图中访问ViewBag数据,如下所示:
<span class="small">@ViewBag.BreadCrumb</span>

我将从代码中发送ViewBag数据,示例代码如下:

ViewBag.BreadCrumb = topic.Category.CatName + " / " + topic.Name;
ViewBag.TopicID = id;

这里的topic是实体。我使用以下代码返回视图:
return View(topic);

但是,它总是向我发送一个异常:
Object reference not set to an instance of an object.

在另一页上,它运行得非常好。有什么解决办法吗?
编辑:
操作代码如下:
Topic topic = db.Topics.FirstOrDefault(t => t.TopicID == id);
ViewBag.Topics = from t in db.Topics where (t.CatID == topic.CatID) select t;
ViewBag.TopicID = id;
ViewBag.BreadCrumb = topic.Category.CatName + " / " + topic.Name;
return View(topic);

编辑::
它显示以下异常:
An exception of type 'System.NullReferenceException' occurred in App_Web_ieekpj10.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

但是在立即窗口中,它显示输出: ViewBag.BreadCrumb "C Sharp Edit / Name- edited to C 12"
编辑::堆栈跟踪
[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Category_NewSection_cshtml.Execute() in e:\OutSourcingStuffs   \OnlineLibrary\src\OnlineLinkLibrary\OnlineLinkLibrary.Web\Views\Category\NewSection.cshtml:12
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +121
System.Web.WebPages.StartPage.RunPage() +63
System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,   TextWriter writer, WebPageRenderingBase startPage) +177
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +762
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +74
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +388
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +72
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +303
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +155
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +66
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +68
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +65
  System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +66
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9688704
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

编辑:查看

@model OnlineLinkLibrary.Models.Section
@{
   ViewBag.Title = "New Section";
}

<div class="panel panel-default">
<div class="panel-heading ">
    <div class="row ">
        <div class="col-xs-6">
            <h4>
                New Section
                <span class="small">@ViewContext.Controller.ViewBag.BreadCrumb</span>
        </h4>
    </div>
    <div class="col-xs-6 ">
        <div class="pull-right"> 
          -- satic htmls are there
        </div>
    </div>
</div>
</div>

1
@Grundy,不仅是topic,还包括topic.Category - alexmac
1
@rughimire请添加完整的操作和视图代码,没有这些代码就无法找到异常原因。 - alexmac
@rughimire 添加视图标记。 - Grundy
2
你确定你发送了正确的模型吗?我看到你发送了Topic类型的模型,但在你的视图中它期望的是OnlineLinkLibrary.Models.Section。 - Mohamed Farrag
1
但视图期望模型!如果您正在使用它,应该发送。 - Mohamed Farrag
显示剩余20条评论
3个回答

5

如果你确定ViewBag 不是null,但是Visual Studio一直指向那行代码为null,

那么看看错误的下一行代码,编译器有时会混淆;)

这可能对于一个懵逼的开发人员有所帮助。


是的,现在我又可以呼吸了。谢谢! - JayJay

0
我建议检查一下主题是否为空。
Topic topic = db.Topics.Where(a=>a.TopicID == id).FirstOrDefault();
if(topic != null)
{
  ViewBag.Topics = from t in db.Topics where (t.CatID == topic.CatID) select t;
}

第二个查询“from t in db.Topics where (t.CatID == topic.CatID) select t;”怎么样,你检查过了吗?它也不是null。 - serhads
1
在这种情况下,我认为问题与“@ViewBag.BreadCrumb”无关。也许您可以关注布局页面或部分视图(如果有的话)。 - serhads

0

你的视图期望一个 OnlineLinkLibrary.Models.Section:

@model OnlineLinkLibrary.Models.Section

但是你提供的主题。除非Topic是OnlineLinkLibrary.Models.Section的子类,否则它不起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接