✅ NullPointException in the Update/Post method, but not in the Get Method
I started feeling puzzled at this NullPointException in this code
[HttpGet] public IActionResult EditListingJ(int? Id) { try { var ListingDTO_DBTable = _context.ListingDTO_DBTable.Find(Id); if (ListingDTO_DBTable != null) { ListingProjectsDTO dtoModelEdit = new ListingProjectsDTO() { Id = ListingDTO_DBTable.Id, ListingName = ListingDTO_DBTable.ListingName }; Console.WriteLine($"Got it"); //The GET method is fine, it grabs the id return Json(dtoModelEdit); } return Json(null); } catch (Exception ex) { return null; } } [HttpPost] public IActionResult EditListingJ(ListingProjectsDTO editedDtoModel) { if (ModelState.IsValid) { //NullPointException!! why does this line stay always null, I don't understand ListingProjectsDTO _listingProjectsDtoEdit = _listingProjectsDtoRepository.getListingProjectsDto(editedDtoModel.Id); _listingProjectsDtoEdit.Id = editedDtoModel.Id; _listingProjectsDtoEdit.ListingName = editedDtoModel.ListingName; _context.ListingDTO_DBTable.Update(_listingProjectsDto); _context.SaveChanges(); return Json(_listingProjectsDto); } return Json(null); }
[HttpGet] public IActionResult EditListingJ(int? Id) { try { var ListingDTO_DBTable = _context.ListingDTO_DBTable.Find(Id); if (ListingDTO_DBTable != null) { ListingProjectsDTO dtoModelEdit = new ListingProjectsDTO() { Id = ListingDTO_DBTable.Id, ListingName = ListingDTO_DBTable.ListingName }; Console.WriteLine($"Got it"); //The GET method is fine, it grabs the id return Json(dtoModelEdit); } return Json(null); } catch (Exception ex) { return null; } } [HttpPost] public IActionResult EditListingJ(ListingProjectsDTO editedDtoModel) { if (ModelState.IsValid) { //NullPointException!! why does this line stay always null, I don't understand ListingProjectsDTO _listingProjectsDtoEdit = _listingProjectsDtoRepository.getListingProjectsDto(editedDtoModel.Id); _listingProjectsDtoEdit.Id = editedDtoModel.Id; _listingProjectsDtoEdit.ListingName = editedDtoModel.ListingName; _context.ListingDTO_DBTable.Update(_listingProjectsDto); _context.SaveChanges(); return Json(_listingProjectsDto); } return Json(null); }
`
In the Get method it grabs the id but the following Post method it does not and crashes into NullPointException. Seems to me like the GET method was able to refer to the row existing in my DB. However that does not seem to be the case for the Post method.