0

Using C# ASP.NET MVC 5.

ProductService (View)

using Shop.Application.ViewModels;
using Shop.Domain.Interfaces;
using System.Linq;

namespace Shop.Application.Services
{
    public class ProductService : IProductService
    {
        private IProductRepository _productRepository;
        public ProductService(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        public ProductViewModel GetProdutcts() =>
            new ProductViewModel()
            {
                Product = _productRepository.GetProducts().ToList(),
            };
    }
}

ProductViewModel

using Shop.Domain.Entities;
using System.Collections.Generic;

namespace Shop.Application.ViewModels
{
    public class ProductViewModel
    {
        public List<Product> Product { get; set; }
    }
}

IProductService

using Shop.Application.ViewModels;

namespace Shop.Application.Services
{
    public interface IProductService
    {
        ProductViewModel GetProdutcts();
    }
}

ProductController

using Microsoft.AspNetCore.Mvc;
using Shop.Application.Services;

namespace Shop.Web.Controllers
{
    public class ProductsController : Controller
    {
        private IProductService _productService;

        public ProductsController(IProductService productService)
        {
            _productService = productService;
        }

        public IActionResult Index() =>
            View(_productService.GetProdutcts());
    }
}

Products Page + bug: (click in link to see the image) Object reference not set to an instance of an object

MY DOUBT: how to fix it?

what i already tried, but didn't work

1 Answers1

-1

In your screenshot (post your code as text) there's a @page directive inside your Razor.

You appear to be mixing "controllers with views" and "Razor Pages". Your controller is never called. Your page is a Razor Page. Your page's OnGet() method in the codebehind (Index.cshtml.cs) needs to populate your model.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272