I try to delete the product and display the error message when the product still related to many tables in database. Here the code :
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
if (_context.Products == null)
{
return Problem("Entity set 'ShoeContext.Products' is null.");
}
var product = await _context.Products.FindAsync(id);
if (product != null)
{
_context.Products.Remove(product);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
if (ex.InnerException?.InnerException is SqlException sqlEx)
{
TempData["ErrorMessage"] = "Cant't Delete This Product";
return RedirectToAction("Index");
}
throw;
}
return RedirectToAction("Index");
}
return RedirectToAction(nameof(Index));
}
In Index.cshtml :
@if (TempData["ErrorMessage"] != null)
{
<div class="alert alert-danger">
@TempData["ErrorMessage"]
</div>
}
But Its alway show like this img . I already use UseSession in Program.cs
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;// Set the session timeout as needed
options.Cookie.IsEssential = true;
});
Does anyone know the problem ? Did I use tempdata or try catch in the wrong way? I really appreciated any instruction. Thank You