MVC/Razor:Viewbag.Title 上的错误

本文关键字:错误 Title Viewbag Razor MVC | 更新日期: 2023-09-27 17:56:41

我有两种方法:

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

两者都使用这个视图:

    @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>

"索引"方法是视图的原始/常用方法。它曾经工作正常。沿着这条线的某个地方,它开始抛出这个错误:

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:  

下面是堆栈跟踪:

    [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

这两种方法都返回有效的对象。它仅在"索引"上出错,而不是在"区域"上出错。索引曾经工作正常。根据本文,我尝试删除 CSharp dll 并重新添加它无济于事。我也回顾了这些文章,但要么与我的问题无关,要么不是我需要的答案:

本文

另一个

MVC/Razor:Viewbag.Title 上的错误

好吧,罪魁祸首是这样的:

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

特别是"ViewContext.RouteData.Values["id"]。ToString()" 行...如果我不传递 ID,它就会在这里轰炸。

感谢大家的想法和方向!

ViewBag.Title 上的 NullReferenceException 可以指示错误确实在附近的行上。在我的情况下,ViewBag 错误在第 6 行 ( @ViewBag.Title )。但实际错误在第 2 行(ViewData["PageHeader"])一旦我从控制器为 PageHeader 设置了视图数据,空引用异常就消失了