System.NullReferenceException: Object reference not set to an instance of an object.

Vote:
 

Hi, I'm following excerise for setting up EPiserver webpage and I've followed every steps and there no red lines errors on the code editor, but when I'm testing the web page it shows error.  

Line 3:  @model PageViewModel<AlloyTraining.Models.Pages.StartPage>
Line 4:  <h1 @Html.EditAttributes(m => m.CurrentPage.Heading)>
Line 5:     @(Model.CurrentPage.Heading ?? Model.CurrentPage.Name)
Line 6:  </h1>
Line 7:  <div>

Source File: c:\Episerver\CMSTraining\AlloyTraining\Views\StartPage\index.cshtml    Line: 5

Stacktrace:

[NullReferenceException: Object reference not set to an instance of an object.]
   ASP._Page_Views_StartPage_index_cshtml.Execute() in c:\Episerver\CMSTraining\AlloyTraining\Views\StartPage\index.cshtml:5
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9836613
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
#225837
Jul 28, 2020 12:12
Vote:
 

It is quite clear that Model.CurrentPage is null. What does your controller look like?

#225870
Jul 29, 2020 6:08
Vote:
 

I have two controllers: PageControllerBase and StartPageController.

PageControllerBase:

using AlloyTraining.Business.ExtensionMethods;
using AlloyTraining.Models.Pages;
using AlloyTraining.Models.ViewModels;
using EPiServer;
using EPiServer.Core;
using EPiServer.Filters;
using EPiServer.Web.Mvc;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;

namespace AlloyTraining.Controllers
{
    public class PageControllerBase<T> : PageController<T> where T : SitePageData
    {
        protected readonly IContentLoader loader;
        public PageControllerBase(IContentLoader loader)
        {
            this.loader = loader;
        }
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }
        protected IPageViewModel<TPage> CreatePageViewModel<TPage>(
        TPage currentPage) where TPage : SitePageData
        {
            var viewmodel = PageViewModel.Create(currentPage);
            viewmodel.Startpage = loader.Get<StartPage>(ContentReference.StartPage);
            viewmodel.MenuPages = FilterForVisitor.Filter(
                loader.GetChildren<SitePageData>(ContentReference.StartPage))
                .Cast<SitePageData>().Where(page => page.VisibleInMenu);
            viewmodel.Section = currentPage.ContentLink.GetSection();
            return viewmodel;
        }
    }
}

StartpageController:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServer.SpecializedProperties;

namespace AlloyTraining.Models.Pages
{
    [ContentType(DisplayName = "Start", GUID = "f41e57f2-67ba-46e0-a0f8-4855ea9208a4", GroupName = SiteGroupNames.Specialized, Order =10, Description = "The home page for a website with an area for blocks and partial pages")]
    [SiteStartIcon]
    public class StartPage : SitePageData
    {
        [CultureSpecific]
        [Display(Name = "Heading", Description = "If the Heading is not set, the page falls back to showing the Name.", 
            GroupName = SystemTabNames.Content, Order =10)]
        public virtual string Heading { get; set; }

        
        [CultureSpecific]
        [Display(
            Name = "Main body",
            Description = "The main body will be shown in the main content area of the page, using the XHTML-editor you can insert for example text, images and tables.",
            GroupName = SystemTabNames.Content,
            Order = 20)]
        public virtual XhtmlString MainBody { get; set; }
         
        [Display(Name = "Main content area",
            Description =" The main content area contains an ordered collection to content references, for example blocks, media assets and pages.",
            GroupName = SystemTabNames.Content, Order =30)]
        public virtual ContentArea MainContentArea { get; set; }
    }
}
#226051
Aug 03, 2020 7:34
Quan Mai - Aug 03, 2020 9:40
You posted code of StartPage, not StartPageController
Vote:
 

Im sorry for sending the wrong code, here is the StartPageController:

using AlloyTraining.Models.Pages;
using EPiServer;
using System.Web.Mvc;

namespace AlloyTraining.Controllers
{
    public class StartPageController : PageControllerBase<StartPage>
    {
        public StartPageController(IContentLoader loader) : base(loader)
        { }

        public ActionResult Index(StartPage currentPage)
        {
            return View(CreatePageViewModel(currentPage));
        }

    }
}
#226056
Aug 03, 2020 10:56
Vote:
 

Hi Daniel,

Try to use ' var viewmodel = PageViewModel<StartPage>.Create(currentPage);' instead of ' var viewmodel = PageViewModel.Create(currentPage);' within the CreatePageViewModel method.

        public class PageControllerBase<T> : PageController<T> where T : SitePageData
        {
            protected readonly IContentLoader loader;
            public PageControllerBase(IContentLoader loader)
            {
                this.loader = loader;
            }
            public ActionResult Logout()
            {
                FormsAuthentication.SignOut();
                return RedirectToAction("Index");
            }
            protected IPageViewModel<TPage> CreatePageViewModel<TPage>(
                TPage currentPage) where TPage : SitePageData
            {
                var viewmodel = PageViewModel<StartPage>.Create(currentPage);
                viewmodel.Startpage = loader.Get<StartPage>(ContentReference.StartPage);
                viewmodel.MenuPages = FilterForVisitor.Filter(
                        loader.GetChildren<SitePageData>(ContentReference.StartPage))
                    .Cast<SitePageData>().Where(page => page.VisibleInMenu);
                viewmodel.Section = currentPage.ContentLink.GetSection();
                return viewmodel;
            }
        }
#226084
Aug 04, 2020 2:49
Vote:
 

Hi Sanjay, thank you for replying.
I've tried your solution, if I change to 'var viewmodel = PageViewModel<StartPage>.Create(currentPage), then the editor gives me red line errors on "viewmodel.Startpage, viewmodel.MenuPages, viewmodel.Section". When I hoover these errors , it says: 'object' does not contain a definition for (startpage, menupages, section) and no accessible extension method (startpage, menupages, section) accepting a first argument of type 'object' could be found(are you missing directive or an assembly reference?)

#226089
Aug 04, 2020 8:43
Sanjay Kumar - Aug 04, 2020 9:59
Okay, then you need to debug the CreatePageViewModel method and find out the reason why the model return null.
Vote:
 

I'm not good at using debugging tool, but is there something here you can see where I can look at "Locals" section?

#226137
Aug 05, 2020 10:06
Vote:
 

What happens if you change line 5 to this:

@(Model.CurrentPage != null ? (Model.CurrentPage.Heading ?? Model.CurrentPage.Name) : "")
#226144
Aug 05, 2020 10:57
Vote:
 

Hi Tomas!
When I change line 5, it still shows error (look at picture below):

#226147
Aug 05, 2020 12:46
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.