Hi! Why my code note update existing data by id?
namespace HRD_Model.Models
{
public class Region
{
[Key]
public int Region_Id { get; set; }
[Required]
[MaxLength(25)]
public string Region_Name { get; set;} = string.Empty;
}
}
RegionController:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Update(Region region, int Id)
{
var existingRegion = await _context.Regions.FirstOrDefaultAsync(e => e.Region_Id == Id);
if (existingRegion == null)
{
return NotFound($"No region found with ID {region.Region_Id}");
}
try
{
_context.Entry(existingRegion).CurrentValues.SetValues(region);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (Exception ex)
{
return StatusCode(500, "An error occurred while updating the region. Details: " + ex.Message);
}
}
View:
@{
ViewData["Title"] = "Update";
}
<h1>Update</h1>
<div class="row">
<div class="col-md-12">
<form method="post" asp-action="Update">
<input type="text" name="Id" value="@Model.Region_Id" />
<div class="form-group">
<label>Region Name</label>
<input type="text" class="form-control" name="Region_Name" placeholder="last name" value="@Model.Region_Name" required>
</div>
<button class="btn btn-success" type="submit">Update Region</button>
</form>
</div>
</div>