kgiszewski / LearnUmbraco7

A book for developers
208 stars 59 forks source link

Custom route and view model return a null reference error #58

Open Stephanie-Spears opened 5 years ago

Stephanie-Spears commented 5 years ago

The Error: Umbraco.Web.UmbracoContext.PublishedContentRequest.get returned null

The code:

public class CategoryController : RenderMvcController
    {
        //Basic Product
        public override ActionResult Index(RenderModel model)
        {
            LogHelper.Info<CategoryController>("Hello, we have a custom model in category.");
            return View(new CategoryModel());
        }        
    }

    public class CategoryModel : RenderModel
    {
        public List<ProductDetailsModel> categoryList;

        public CategoryModel()
            : base(UmbracoContext.Current.PublishedContentRequest.PublishedContent)
        {
            categoryList = NopCommerceService.Instance.GetNopProducts().Products;
        }
    }
skttl commented 5 years ago

Hi Stephanie

You need to add your PublishedContent as a parameter for the new CategoryModel() you have.

This should work.

public class CategoryController : RenderMvcController
    {
        //Basic Product
        public override ActionResult Index(RenderModel model)
        {
            LogHelper.Info<CategoryController>("Hello, we have a custom model in category.");
            return View(new CategoryModel(model.Content));
        }        
    }

    public class CategoryModel : RenderModel
    {
        public List<ProductDetailsModel> categoryList;

        public CategoryModel()
            : base(UmbracoContext.Current.PublishedContentRequest.PublishedContent)
        {
            categoryList = NopCommerceService.Instance.GetNopProducts().Products;
        }
    }