You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多Action方法关联单个View时Delete操作的视图异常问题

解决ASP.NET MVC中Delete操作的视图缺失与Action歧义问题

咱们一步一步拆解你的问题,搞定这两个坑:

第一个问题:点击Delete链接提示找不到Delete视图

你点击表格里的ActionLink触发的是GET请求,会直接调用这个方法:

//GET:
public ActionResult Delete(int? id) { 
    // ***code goes here**** 
    return View(lansing); 
}

这个方法最后返回了View(lansing),ASP.NET MVC会默认去查找/Views/[ControllerName]/Delete.cshtml视图文件,但你显然没创建这个视图,所以触发报错。

解决思路二选一:

  1. 创建Delete视图:如果需要一个确认删除的页面,就新建Delete.cshtml,展示要删除的对象信息,再添加一个确认删除的POST表单。
  2. 直接用POST删除(更推荐):删除属于修改数据的操作,用GET存在安全风险(比如被爬虫误触发)。把表格里的ActionLink换成表单,用POST请求提交到Delete的POST方法,示例代码如下:
    @using (Html.BeginForm("Delete", "YourControllerName", new { id = item.Id }, FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        <button type="submit" onclick="return confirm('确定要删除吗?');">删除</button>
    }
    
    这样点击按钮就直接触发POST Delete,跳过GET Delete的视图问题。

第二个问题:POST Delete加ActionName("Index")后出现歧义

你现在有两个POST方法都标记了[ActionName("Index")]:

[HttpPost, ActionName("Index")]
[OnAction(ButtonName = "Create")]
public ActionResult Index(***code goes here***) { ... }

[HttpPost, ActionName("Index")]
[OnAction(ButtonName = "Delete")]
public ActionResult Delete(int id) { ... }

ASP.NET MVC的路由系统无法区分这两个同名的POST方法,所以报歧义错误。

解决方法:

去掉ActionName("Index"),让两个POST方法保持各自的名称,再通过表单的action属性指定对应的Action:

  • Create操作的表单提交到Index的POST方法(保留你原来的逻辑)
  • Delete操作的表单提交到Delete的POST方法(就是上面写的表单)

另外,记得把[ValidateAntiForgeryToken]加回Delete的POST方法里,这是安全最佳实践。

如果一定要在同一个Action里处理Create和Delete(比如用同一个表单的不同按钮),可以不用ActionName,而是在Action方法里判断按钮名称:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(YourViewModel model, string button)
{
    if (button == "Create")
    {
        // 处理创建逻辑
        return RedirectToAction("Index");
    }
    else if (button == "Delete")
    {
        // 从模型或隐藏字段获取要删除的ID
        int deleteId = model.DeleteId;
        // 处理删除逻辑
        return RedirectToAction("Index");
    }
    return View(model);
}

这种方式需要给每个按钮设置name="button",示例:

<button type="submit" name="button" value="Create">创建</button>
<button type="submit" name="button" value="Delete">删除</button>

总结最优流程:

  1. 表格里的删除操作改用POST表单(带AntiForgeryToken),直接提交到Delete的POST方法,避免GET请求的安全问题和视图缺失问题。
  2. 让Create和Delete的POST方法保持各自的Action名称,避免路由歧义。

内容的提问来源于stack exchange,提问作者Dominik Willaford

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:27:21