【问题标题】:Am I using HttpGet and HttpPost wrong? ASP.NET C#我使用 HttpGet 和 HttpPost 错了吗? ASP.NET C#
【发布时间】:2019-12-03 09:37:02
【问题描述】:

代码:

[HttpPost]
public ActionResult DeleteProduct(int ProductID, string Name, decimal Price, string Photo, int Likes, string Description, Enums.ProductCategory.Category Category) 
{
    ProductModel productModel = new ProductModel
    {
        ProductID = ProductID,
        Name = Name,
        Price = Price,
        Photo = Photo,
        Likes = Likes,
        Description = Description,
        Category = Category
    };
    return View(productModel); 
}
[HttpGet]
public ActionResult DeleteProduct(int ProductID)
{
    if(UserController.userSessionID != 0)
    {
        user.DeleteProduct(ProductID);
        return RedirectToAction("ViewSellerProducts", "Product");
    }
    return View();
}

但我读到 HttpGet 只用于获取数据而不做任何其他事情,[HttpGet]DeleteProduct() 没有这样做。事实是,如果我将DeleteProduct() 更改为[HttpPost],ID 将为 0,那么如何在视图中获取 ID?

当产品设置在页面上时:

当我在显示所有详细信息的页面上时,我必须点击删除:

【问题讨论】:

  • 1.奇怪的是,您将第一个 DeleteProduct 操作方法注释为 HttpPost,将第二个 DeleteProduct 方法注释为 HttpGet。 IMO,第一个应该是HttpGet,第二个应该是HttpPost。 2.另外,请将您的截图图像替换为代码(文本)。否则,很可能有人会对此投反对票。
  • @itminus 我知道这更有意义,但是当我将第二个删除更改为 HttpPost 时,我没有得到 ProductID,我只得到 0。
  • 还有你为什么要在删除或获取中发布数据而不是 id,又名Name = Name, Price = Price, Photo = Photo, Likes = Likes, Description = Description, Category = Category 可能不需要

标签: asp.net-core model-view-controller http-get


【解决方案1】:

您缺少 input 和产品 ID 以将其传递为 HttpPost

<form asp-action="DeleteProduct">
    <input type="hidden" asp-for="ProductID" />
    <input type="submit" value="Delete" class="btn btn-danger" />
    ...
</form>

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多