NullReferenceException while accessing ViewBag in Asp.net MVC4
Asked Answered
M

3

7

I am trying to access the ViewBag data in my view as below:

<span class="small">@ViewBag.BreadCrumb</span>

I am sending that ViewBag data from code like:

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

Here, topic is the Entity. And I am returning the View using:

return View(topic);

But, it always send me an exception:

Object reference not set to an instance of an object.

In another page it's working very well. Is there any solution?

Edit::

Code of Action is as follows:

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);

Edit::

Its shows following exception:

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.

But in in Immediate windows it shows output: ViewBag.BreadCrumb "C Sharp Edit / Name- edited to C 12"

Edit:: Stack Trace

[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

Edit: View

@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>
Morello answered 27/2, 2014 at 7:36 Comment(25)
are you sure that topic not null?Untouchability
@Untouchability , not only topic, but topic.Category tooCotta
Then he would get the exception on the ViewBAg.BreadCrumb =... line not in the view. As I read the question that is the location this happens. The ViewBag seems to be null.Walloon
possibly, ViewBag.BreadCrumb is not getting any value, put a breakpoint there and check.Petrarch
Is the exception being thrown in the Controller or the View?Harewood
@Morello add complete code of action and view, without these is not possible to find the exception reason.Cotta
The exception is being thrown in View.Morello
I have added full code of the ActionMorello
Have you tried accessing ViewBag.Topics & ViewBag.TopicID in your view ? Do you get error for them also ?Overscore
@Morello add view markup alsoUntouchability
@Vaibha and All, If I remove, <span class="small">@ViewBag.BreadCrumb</span> it throws exception to ViewBag.Title.Morello
try to use @ViewContext.Controller.ViewBag.TitleOverscore
@vaibhav, still not solved using ContextMorello
Edited to provide more details- please helpMorello
try clean project and rebuildUntouchability
do you use any 3rd-party libraries in your app?Untouchability
I am using EF code first and Angular js and dont think they are making issues. The same things are working in all other views. Just a problem with this. I also clean the solution, still no solution.Morello
@Grundy, Can you please check the stack trace.Morello
@Morello can you provide NewSection.cshtml?Untouchability
it seems ok. if you remove all calling ViewBag from this it work?Untouchability
exception only this view? try find defferent from another views that works fineUntouchability
can you provide layout also?Untouchability
are you sure that you sent the right Model ? I can see you sent model of kind Topic and in your view it expects OnlineLinkLibrary.Models.SectionPerquisite
@Mohamed , I also tried without sending Model to view. It does not workMorello
but the view expects the Model !. you should send if you are using it.Perquisite
Q
6

If you are sure by 100% that the ViewBag is not null however Visual Studio keeps pointing to that line as null,

then look at the next line of code for the error, the compiler sometimes get confused ;)

This might help a drowning dev.

Quattrocento answered 20/7, 2017 at 9:34 Comment(1)
Yeah now I am breathing again. Thanks!Diegodiehard
M
0

I would suggest check if topic is null or not.

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;
}
Mausoleum answered 27/2, 2014 at 8:4 Comment(2)
how about second query "from t in db.Topics where (t.CatID == topic.CatID) select t;" have you checked, it is also not nullMausoleum
In this case I don't think the problem is releted with "@ViewBag.BreadCrumb". Maybe you can focus on layout page or partialView if page has.Mausoleum
L
0

Your view is expecting a OnlineLinkLibrary.Models.Section:

@model OnlineLinkLibrary.Models.Section

But you provide a Topic. Unless Topic is a subclass of OnlineLinkLibrary.Models.Section, it wouldn't work.

Litton answered 27/2, 2014 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.