1

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.

Serge
  • 40,935
  • 4
  • 18
  • 45
  • 2
    There is nothing wrong or ugly about hidden fields. HTTP is stateless so you have to pass all the values you need back and forth from client to server. If you don't want to show the id then you make it hidden. – Crowcoder Jun 15 '21 at 12:45

1 Answers1

1

try to add a hidden field

<form asp-action="Edit" asp-controller="Products" method="post">
  <input asp-for="ProductId" type="hidden" value="@Model.ProductID" />
.......
Serge
  • 40,935
  • 4
  • 18
  • 45