为什么我得到状态码:405;尝试执行删除操作后不允许方法?
Why did i get Status Code: 405; Method Not Allowed after trying to execute the delete action?
ASP.NET 核心 5.0,EF 核心 5.0
我的行动:
[HttpPost("id")]
public IActionResult DeleteEquipment(int id)
{
repository.DeleteEquipment(id);
return View("WorkoutDB");
}
我的 ef 方法:
public void DeleteEquipment(int Id)
{
_context.Remove(new Equipment() { EquipmentId = Id });
_context.SaveChanges();
}
局部视图中的我的按钮:
<input type="button" value="Delete" class="btn btn-danger" onclick="location.href='@Url.Action("DeleteEquipment", "Admin", item.EquipmentId)'" /
不知道是不是正常的代码,我是新手,但是我花了4个小时没有得到结果。
感谢您的关注!
更新:
我改变了我的按钮
<td>
<form asp-action="DeleteEquipment" method="post">
<input type="hidden" name="EquipmentId" value="@item.EquipmentId" />
<button type="submit" class="btn btn-danger btn-sm">
Delete
</button>
</form>
</td>
但是还是不行。我无法将正确的值绑定到 EquipmentId。始终为 0 值。为什么?
location.href='@Url.Action("DeleteEquipment", "Admin", item.EquipmentId)' 导致浏览器将用户重定向到新 url。重定向导致 GET 请求,但您的 DeleteEquipment 方法具有 HttpPost 属性。
替换
[HttpPost("id")]
和
[HttpGet("{id}")]
正如@mason 提到的,如果您需要使用 POST 请求调用您的 api,您需要使用表单。
<form asp-action="DeleteEquipment" asp-controller="Admin" asp-route-id="@item.EquipmentId">
<input type="submit" class="btn btn-danger" value="Delete" />
</form>
ASP.NET 核心 5.0,EF 核心 5.0 我的行动:
[HttpPost("id")]
public IActionResult DeleteEquipment(int id)
{
repository.DeleteEquipment(id);
return View("WorkoutDB");
}
我的 ef 方法:
public void DeleteEquipment(int Id)
{
_context.Remove(new Equipment() { EquipmentId = Id });
_context.SaveChanges();
}
局部视图中的我的按钮:
<input type="button" value="Delete" class="btn btn-danger" onclick="location.href='@Url.Action("DeleteEquipment", "Admin", item.EquipmentId)'" /
不知道是不是正常的代码,我是新手,但是我花了4个小时没有得到结果。 感谢您的关注!
更新: 我改变了我的按钮
<td>
<form asp-action="DeleteEquipment" method="post">
<input type="hidden" name="EquipmentId" value="@item.EquipmentId" />
<button type="submit" class="btn btn-danger btn-sm">
Delete
</button>
</form>
</td>
但是还是不行。我无法将正确的值绑定到 EquipmentId。始终为 0 值。为什么?
location.href='@Url.Action("DeleteEquipment", "Admin", item.EquipmentId)' 导致浏览器将用户重定向到新 url。重定向导致 GET 请求,但您的 DeleteEquipment 方法具有 HttpPost 属性。
替换
[HttpPost("id")]
和
[HttpGet("{id}")]
正如@mason 提到的,如果您需要使用 POST 请求调用您的 api,您需要使用表单。
<form asp-action="DeleteEquipment" asp-controller="Admin" asp-route-id="@item.EquipmentId">
<input type="submit" class="btn btn-danger" value="Delete" />
</form>