I feel like starting to bang my head against my keyboard after many months of Googling and posting in other forums. So I really appreciate any insights.
My problem is that as mentioned in the title the edit http POST
method does not save user inputs once the save button is clicked on browser. This video illustrates my point: https://imgur.com/a/GWBHXp1
I tried debugging my code here:
[HttpGet]
public JsonResult EditListingJ(int Id) //For getting details of the selected User
{
try
{
var ListingDTO_DBTable = _context.ListingDTO_DBTable.Find(Id);
if (ListingDTO_DBTable != null)
{
Console.WriteLine($"Got it");
return Json(ListingDTO_DBTable);
}
return Json(null);
}
catch (Exception ex)
{
Console.WriteLine("so null nothing can be edited");
return null;
}
}
[HttpPost]
public JsonResult EditListingJ(int Id, ListingProjectsDTO _listingProjectsDto) //For Updating changes
{
try
{
var ListingDTO_DBTable = _context.ListingDTO_DBTable.Find(Id); //fetching the user with Id
if (ListingDTO_DBTable != null)
{
_context.ListingDTO_DBTable.Update(ListingDTO_DBTable); //deleting from db
_context.SaveChanges();
Console.WriteLine("saving finally success");
return Json(ListingDTO_DBTable);
}
}
catch (Exception ex)
{
Console.WriteLine("saving failed");
return null;
}
Console.WriteLine("saving failed too");
return Json(_listingProjectsDto);
}
And it gave me this output
Console.WriteLine("saving failed too")
which means my edit has not been saved anywhere. A little more digging found out that
var ListingDTO_DBTable = _context.ListingDTO_DBTable.Find(Id);
returns null.
Could anyone kindly point out me in the right direction? No idea why those lines went to null etc.
A pair programming with another developer finally solved this issue with the edited string not passed onto the controller.
Fix #1: We had to add this line into my Program.cs
builder.Services.AddControllers()
.AddNewtonsoftJson(opt =>
{
opt.SerializerSettings.ContractResolver = new DefaultContractResolver(); // RESOLVES CASING ISSUES
});
We realised that my db was using lowercases only to save the data where my controller (EF) does use both lowercases and uppercases. The DefaultContractResolver addresses this conflict.
Fix #2 In my cshtml we added this
<div id="EditDashboardNow" method="post" name="editSubmitId">
<form method="post" asp-controller="Home" asp-action="EditListingJpost" enctype="multipart/form-data">
/* more cshtml elements */
</form>
<div>
The problem has been my post method in my EF not passing the value to db (henceforth no updates for user inputs). asp-action="EditListingJpost" method="post" These two marks passed the Id value onto the controller.
I hope this post assists others with similar issues ^^