Delete post方法返回null



我正在学习如何使用asp.net mvc制作一个简单商店的初学者教程,在教程中,执行完全相同的步骤是没有问题的。我目前正在尝试在我的类别页面上执行基本的CRUD操作,但在尝试删除类别时遇到了问题。我找不到页面,因为id为null,但当传递相同的id参数时,我对Edit方法没有问题。我一直在寻找答案,有些人认为可能存在缓存问题,但不确定如何解决这个问题。这是我的控制器删除操作

// GET-DELETE
public IActionResult Delete(int? id)
{

if (id == null || id == 0)
{
return NotFound();
}
Category obj = _db.Category.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
//POST-DELETE
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? id)
{
Category obj = _db.Category.Find(id);
if (id == null)
{
return NotFound();
}


_db.Category.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");


}

这是我的View

@model RockyWebsite.Models.Category
<form method="post" asp-action="DeletePost">
@Html.HiddenFor(id => id.CategoryId)
<input asp-for="CategoryId" hidden />
<div class="border p-3">
<div class="form-group row">
<h2 class="text-info pl-3">Delete Category</h2>
</div>
<div class="row">
<div class="col-8">
<div class="form-group row">
<div class="col-4">
<label asp-for="CategoryName"></label>
</div>
<div class="col-8">
<input asp-for="CategoryName" disabled class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label asp-for="DisplayOrder"></label>
</div>
<div class="col-8">
<input asp-for="DisplayOrder" disabled class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-4 row">
<div class="col">
<input type="submit" class="btn btn-danger w-100" value="Delete" />
</div>
<div class="col">
<a asp-action="Index" class="btn btn-success w-100"><i class="fas fa-sign-out-alt"></i> Back</a>
</div>
</div>
</div>
</div>
<div class="col-4">
@* Keep this empty *@
</div>
</div>
</div>
</form>

如有任何帮助或建议,我们将不胜感激,谢谢!

您在视图中使用@Html.HiddenFor(id => id.CategoryId)(好吧,实际上您也使用了标记辅助语法<input asp-for="CategoryId" hidden />,您应该只使用其中一个,而不是同时使用两个!(,这将使用name="CategoryId"创建输入。

因此,最简单的解决方案可能是在DeletePost的控制器操作中更正视图并更新参数名称。

视图:

<!-- remove this line: @Html.HiddenFor(id => id.CategoryId) -->
<!-- just use line below -->
<input type="hidden" asp-for="CategoryId" />

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int? categoryId)
{
Category obj = _db.Category.Find(categoryId);
// check obj here, not id
if (obj == null)
{
return NotFound();
}    

_db.Category.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}

用这个替换表单标签

@Html.BeginForm("DeletePost", "controllerName", FormMethod.Post,
new {id="@Model.CategoryId"})
{
@Html.AntiForgeryToken()

和动作

[HttpPost("{id}")]
[ValidateAntiForgeryToken]
public IActionResult DeletePost(int id)

将name标记添加到输入中,例如:

<input name="id" asp-for="CategoryId" hidden />

Alex

最新更新