I tried to edit the Products table using two methods, but POST method recieve model with ProductID equal 0.
All I found on my question is this suggestion to use a hidden field, but this solution looks ugly.
Could you suggest a more concise solution?
Methods in controller:
[HttpGet]
public async Task<IActionResult> Edit(int? id)
{
if (id != null)
{
Product product = await _db.Products.FirstOrDefaultAsync(p => p.ProductID == id);
if (product != null)
{
return View(product);
}
}
return NotFound();
}
[HttpPost]
public async Task<IActionResult> Edit(Product product)
{
if (ModelState.IsValid)
{
_db.Products.Update(product);
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
else
{
return View(product);
}
}
Model:
public class Product
{
[Key]
public int ProductID { get; set; }
[Required]
[StringLength(40)]
public string ProductName { get; set; }
}
View:
@model Product
@{
ViewData["Title"] = "Edit product";
}
<h2>@ViewData["Title"]</h2>
<form asp-action="Edit" asp-controller="Products" asp-route-id="@Model.ProductID">
<div class="input-group-sm col-sm-6">
<label asp-for="ProductName">Product name</label>
<input asp-for="ProductName" class="form-control" />
<span asp-validation-for="ProductName"></span>
</div>
</form>
Source code without cutting on GitHub .
try to add a hidden field
<form asp-action="Edit" asp-controller="Products" method="post">
<input asp-for="ProductId" type="hidden" value="@Model.ProductID" />
.......
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.