0

Here is my ViewModels

   namespace SiparisApps.Models.ViewModels
{
    public class OrderVM
    {
        public OrderProduct OrderProduct { get; set; }
        public IEnumerable<OrderDetails> OrderDetails { get; set; }  
    }
}

Here is my Controller

namespace SiparisApps.Areas.Admin.Controllers
{   
    [Area("Admin")]
    public class OrderController : Controller
    {
        private readonly IUnitOfWork _unitOfWork;
        public OrderVM OrderVM { get; set; }
        public OrderController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork; 
        }

        public IActionResult Index()
        {
            var orderList = _unitOfWork.OrderProduct.GetAll(x=>x.OrderStatus != "Delivered");
            return View(orderList);
        }

        /* to view the details from the admin panel */
        public IActionResult Details(int orderId)
        {
            OrderVM = new OrderVM()
            {
                OrderProduct = _unitOfWork.OrderProduct.GetFirstOrDefault(o => o.Id == orderId, includeProperties: "AppUser"),
                OrderDetails = _unitOfWork.OrderDetails.GetAll(d => d.OrderProductId == orderId, includeProperties: "Product")
            };
            return View(OrderVM);

        }

**And this is where i got the error **

@model SiparisApps.Models.ViewModels.OrderVM
    <input value="@Model.OrderProduct.OrderDate.ToShortDateString()" readonly type="text" class="form-control" />

I get this error in my Details ViewPage when I click details on my own site => " System.NullReferenceException: 'Object reference not set to an instance of an object.'

SiparisApps.Models.ViewModels.OrderVM.OrderProduct.get returned null. "

How can I fix this problem ?

  • GetFirstOrDefault *may* return a `null`... – Hans Kesting Jul 21 '22 at 17:00
  • Please help me I couldn't solve this and I don't think the problem is caused by GetFirstOrDefault.. – Oguz Akcay Jul 21 '22 at 19:11
  • 1
    If you execute `_unitOfWork.OrderProduct.GetFirstOrDefault(o => o.Id == orderId, includeProperties: "AppUser")` for a value of `orderId` that does not match a row, then `GetFirstOrDefault()` will return a `null` and cause the error you are seeing in your view. The problem is not `GetFirstOrDefault()` -- the problem is the value of `orderId`. – David Tansey Jul 22 '22 at 05:11
  • Thank you David.You are right.The problem has solved.. – Oguz Akcay Jul 22 '22 at 09:44

0 Answers0