C
C#7mo ago
IamMax420

I'm getting an error "object reference not set to an instance of an object"

the code: @model IEnumerable<WebApp.Models.Produkt> <h1>a List</h1> @if (Model == null || !Model.Any()) { <p>No products available.</p> } else { @foreach (var product in Model) { if (product != null) { <li> <b>@product.name</b> - @product.category <a href="@Url.Action("Details", "Warehouse", new { id = product.id })">Details</a> <button>Delete</button> </li> } } } It appears that Model is null but I don't know how to fix it
7 Replies
Angius
Angius7mo ago
What's the controller?
IamMax420
IamMax420OP7mo ago
You mean the controller name? it's WarehouseController
Angius
Angius7mo ago
The code You seem to not be sending any data to the view
IamMax420
IamMax420OP7mo ago
here's the code: using Microsoft.AspNetCore.Mvc; using WebApp.Models; using WebApp.Services.Interfaces; namespace WebApp.Controllers { public class WarehouseController : Controller { private readonly IWarehouseService _warehouseService; public WarehouseController(IWarehouseService warehouseService) { _warehouseService = warehouseService; } public IActionResult Index() { return View(); } [HttpGet] public IActionResult Add() { return View(); } [HttpPost] public IActionResult Add(Produkt body) { if(!ModelState.IsValid) { return View(body); } //logika do zapisu produktu var id = _warehouseService.Save(body); ViewData["ProductId"] = id; TempData["ProductId"] = id; return RedirectToAction("List1"); } [HttpGet] public IActionResult List1() { var products = _warehouseService.GetAllProdukts(); return View(); } [HttpGet] public IActionResult Details(int id) { var product = _warehouseService.Get(id); return View(); } [HttpDelete] public IActionResult Delete(int id) { _warehouseService.Delete(id); return RedirectToAction("List1"); } } }
Angius
Angius7mo ago
And which action gives you a null?
IamMax420
IamMax420OP7mo ago
these two: [HttpGet] [HttpGet] public IActionResult List1() { var products = _warehouseService.GetAllProdukts(); return View(); } [HttpGet] public IActionResult Details(int id) { var product = _warehouseService.Get(id); return View(); } but after doing return View(products); and return View(product) respectively, it seems to be working now crazy how sometimes such small oversights can cost you 30 mins or even an hour of trying to figure out what is going on lol thanks though @ZZZZZZZZZZZZZZZZZZZZZZZZZ
Angius
Angius7mo ago
Yeah, I was about to point you to the fact that you don't pass anything to the view in most of those actions lol Glad you noticed it
Want results from more Discord servers?
Add your server