0

I have two methods:

public ActionResult Index()
{
    var propList = db.Properties
        .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate) 
            || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate'
        .ToList();
    // Use view model
    var pDVMs = DomainModelsToViewModels(propList);
    return View(pDVMs);
}

public ActionResult Region(string id) // (regionId/marketId)
{
    // make sure to replace the hyphens in the name
    int marketId = db.Markets.Where(x => x.Name == id.Replace("-"," ")).FirstOrDefault().MarketID;
    var tempList = db.Properties
        .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate)
            || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate'
        .ToList();
    var propList = tempList.Where(x => x.MarketId == marketId).ToList();
    // Use view model
    var pDVMs = DomainModelsToViewModels(propList);
    return View("Index", pDVMs);
}

Both use this one view:

    @model IEnumerable<woolbrightcorporatecms.viewmodels.propertydetailsviewmodel>

    @{
    ViewBag.Title = "Portfolio";
    }

    <h2 class="mapOverlay">Portfolio of Properties</h2>

    <!-- Main map here with multiple 'markers'-->
    <div class="container-full">
        <div id="map_canvas" style="height: 320px;" class="row"></div>
    </div>

    <div class="text-center" style="font-size: 32px; line-height: 38px; color: #FC543E;">Filter Region</div>
    <div class="text-center" style="color:#5D6067; font-size: 14px; line-height: 17px;">Please choose from the following</div>

    <br /><br />

    <ul class="list-inline text-center propertyRegionUL">
        <li data-marketid="Miami-Dade" class="regionLI @(ViewContext.RouteData.Values[" id"].tostring()= ="Miami-Dade" ? "active"
            "" )">Miami Dade</li>
        <li data-marketid="Fort-Lauderdale" class="regionLI @(ViewContext.RouteData.Values[" id"].tostring()= ="Fort-Lauderdale" ? "active"
            "" )">Fort Lauderdale</li>
        <li data-marketid="West-Palm-Beach" class="regionLI @(ViewContext.RouteData.Values[" id"].tostring()= ="West-Palm-Beach" ? "active"
            "" )">West Palm Beach</li>
        <li data-marketid="Tampa" class="regionLI @(ViewContext.RouteData.Values[" id"].tostring()= ="Tampa" ? "active"
            "" )">Tampa</li>
        <li data-marketid="Orlando" class="regionLI @(ViewContext.RouteData.Values[" id"].tostring()= ="Orlando" ? "active"
            "" )">Orlando</li>
    </ul>
    <br /><br />

    @* show prop name/city name 4 rows across *@
    <div class="propertyListWrapper text-center table col-md-8 col-md-offset-2">
        @{int columnCount = 0;}
        @foreach (var item in Model)
        {
        if (columnCount == 0)
        {
        @:<div class="row">
            }
            <div style="display:inline-block;" class="col-sm-2">
                <div class="propertyListName">
                    <a href='@(Url.Action("Details", "Property", new { id = item.PropertyId }))'>@(item.Name)</a>
                </div>
                <div class="propertyListCity">
                    <a href='@(Url.Action("Details", "Property", new { id = item.PropertyId }))'>@(item.City)</a>
                </div>
            </div>
            if (columnCount == 3)
            {
            @:
        </div>
        }
        columnCount++;
        if (columnCount == 4)
        {
        columnCount = 0;
        }
        }
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            // initialize map to center on florida.
            initializeGMap();
            // serialize model locations
            var locationsToPass = @Html.Raw(Json.Encode(Model.Select(x => new { x.Name, x.Location.Latitude, x.Location.Longitude })));
            // drop markers
            addMarker(locationsToPass);
            // filter by region/market
            $('li.regionLI').click(function (ev) {
                ev.preventDefault(); // just in case we decide to use anchor tags
                // get id from element clicked AND make sure to reset previous values with 'new { id=""}' else it will append/
                var url = '@(Url.Action("Region", "Property", new { id = "" }))/' + $(this).data('marketid');
                window.location.href = url;
            });
        });
    </script>

The 'Index' method is the original/stock method for the view. It used to work fine. Somewhere along the line it started throwing this error:

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 4:  
Line 5:  @{
Line 6:      ViewBag.Title = "Portfolio"; <-- HERE is where it errors
Line 7:  }
Line 8:  

Here's the stack trace:

    [NullReferenceException: Object reference not set to an instance of an object.]
   ASP._Page_Views_Property_Index_cshtml.Execute() in c:\Users\bdamore.WDI\Source\WoolbrightCorporateCMS\WoolbrightCorporateCMS\Views\Property\Index.cshtml:4
   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) +131
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
   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.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<begininvokeaction>
    b__1c() +321
    System.Web.Mvc.Async.<>c__DisplayClass21.<begininvokeaction>
        b__1e(IAsyncResult asyncResult) +185
        System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
        System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
        System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
        System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
        System.Web.Mvc.Controller.<beginexecutecore>
            b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
            System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
            System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
            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) +44
            System.Web.Mvc.Controller.<beginexecute>
                b__15(IAsyncResult asyncResult, Controller controller) +39
                System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
                System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
                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) +39
                System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
                System.Web.Mvc.MvcHandler.<beginprocessrequest>
                    b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
                    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
                    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
                    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) +40
                    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
                    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651796
                    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Both methods are returning valid objects. It only errors on 'Index', not on 'Region'. Index used to work fine. I tried removing the CSharp dll and re-adding it to no avail as per this article. I've also reviewed these articles but either not pertaining to my problem or not the answer I need:

This article

Another one

Community
  • 1
  • 1
Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56
  • that is correct, it is being set in the view. Please see above – Beau D'Amore Jun 17 '15 at 14:21
  • Try to create a *minimal* set of code that continues to cause the error. For this, I'd suggest a new action+view that doesn't even have a viewmodel. Then you can ignore all the confusing and most likely irrelevant model loading – freedomn-m Jun 17 '15 at 14:25
  • `ViewBag` is never null, so `ViewBag.Title = "Portfolio"` will never throw that exception. Show your actual code. Do you actually use `ViewBag.Title = Model.FirstOrDefault().SomeProperty`? – CodeCaster Jun 17 '15 at 14:25
  • 1
    Can you put a breakpoint on the line `ViewBag.Title = .....`. Debug the site in Visual Stuiod, hit that breakpoint and check if `ViewBag` is `NULL`. – Jason Evans Jun 17 '15 at 14:26
  • No I don't. This is all the code there is. I added the full Razor view – Beau D'Amore Jun 17 '15 at 14:26
  • It's probably another property trying to be accessed in the view and no the `ViewBag` itself. – area28 Jun 17 '15 at 14:26
  • Viewbag isn't null, just checked. I also stripped everything out of the view completely and it loaded (albeit blank)... so something else is wrong in the razor – Beau D'Amore Jun 17 '15 at 14:28
  • I got it... Thanks for the hints everyone. It was the 'Region Menu' trying to access Viewcontext.RouteData.Values["id"] because id isn't passed from Index, just form 'Region'... I'll post answer now. – Beau D'Amore Jun 17 '15 at 14:31

2 Answers2

1

Ok, the culprit was this:

  <ul class="list-inline text-center propertyRegionUL">
    <li data-marketid="Miami-Dade" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Miami-Dade" ? "active" : "")">Miami Dade</li>
    <li data-marketid="Fort-Lauderdale" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Fort-Lauderdale" ? "active" : "")">Fort Lauderdale</li>
    <li data-marketid="West-Palm-Beach" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "West-Palm-Beach" ? "active" : "")">West Palm Beach</li>
    <li data-marketid="Tampa" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Tampa" ? "active" : "")">Tampa</li>
    <li data-marketid="Orlando" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Orlando" ? "active" : "")">Orlando</li>
</ul>

specifically the "ViewContext.RouteData.Values["id"].ToString()" lines... if I 'm not passing an id, it's bombing here.

Thanks to everyone for the ideas and direction!

Beau D'Amore
  • 3,174
  • 5
  • 24
  • 56
  • 1
    I strongly suggest you consider using [viewmodels](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) to store the route value data, rather than directly calling `ViewContext.RouteData.Values.....` in the view itself. – Jason Evans Jun 17 '15 at 14:35
0

A NullReferenceException on ViewBag.Title can indicate the error is really on a nearby line. In my case ViewBag error was on line 6 ( @ViewBag.Title ). But the actual error was on line 2 ( ViewData["PageHeader"] ) Once I set the view data for PageHeader from the controller, the null reference exception was gone

Ananth
  • 10,330
  • 24
  • 82
  • 109