【问题标题】:POST method receive an Entity with Id equal 0POST 方法接收 Id 等于 0 的实体
【发布时间】:2021-08-31 07:28:45
【问题描述】:

我尝试使用两种方法编辑 Products 表,但 POST 方法接收到 ProductID 等于 0 的模型。

我在问题中发现的只是使用隐藏字段的建议,但 this solution 看起来很难看。

您能提出一个更简洁的解决方案吗?

控制器中的方法:

[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);
    }
}

型号:

public class Product
{
    [Key]
    public int ProductID { get; set; }

    [Required]
    [StringLength(40)]
    public string ProductName { get; set; }
}

查看:

@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>

源代码不切GitHub。

【问题讨论】:

  • 隐藏字段没有错或丑陋。 HTTP 是无状态的,因此您必须从客户端到服务器来回传递所需的所有值。如果您不想显示 id,则将其隐藏。
  • @Crowcoder 好的,谢谢你的解释

标签: c# .net-core entity-framework-core asp.net-core-mvc


【解决方案1】:

尝试添加隐藏字段

<form asp-action="Edit" asp-controller="Products" method="post">
  <input asp-for="ProductId" type="hidden" value="@Model.ProductID" />
.......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多