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

使用RouteAttribute时表单无法提交,请求提交至错误Action的问题

解决RouteAttribute下表单提交至非预期Action的问题

嘿,我帮你定位下问题所在:你给GET的Create方法配置了自定义路由[Route("CreateDocument/{personId}")],但POST版本的Create完全没加路由属性。这就导致表单提交时,路由系统找不到和提交路径匹配的POST Action,只能匹配到其他符合条件的Action,自然就出现了提交到非预期方法的问题。

下面给你两个靠谱的解决方案:

方案1:给POST Action加上匹配的路由属性

直接给POST的Create方法也加上和GET一致的路由模板,让请求能精准匹配到它:

[HttpPost]
[Route("CreateDocument/{personId}")] // 新增这个路由,和GET的路由保持一致
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,PersonId,DateReceived,Documentation...")] PersonDocumentation personDocumentation)
{
    if (ModelState.IsValid)
    {
        db.PersonDocumentations.Add(personDocumentation);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    // 重新渲染视图时别忘了回显下拉框数据
    ViewBag.DocumentationTypeIdSelection = new SelectList(db.DocumentationTypes, "Id", "DocumentationTypeName", personDocumentation.DocumentationTypeId);
    return View(personDocumentation);
}

方案2:确保视图表单的提交路径正确

另外,也要检查视图里的表单是否用正确的方式生成提交路径,推荐用Html.BeginForm结合路由参数生成,避免硬编码路径出错:

@using (Html.BeginForm("Create", "ControllerName", new { personId = Model.PersonId }, FormMethod.Post, new { }))
{
    @Html.AntiForgeryToken()
    
    <!-- 这里放你的表单控件,比如PersonId隐藏域、日期选择器等 -->
    @Html.HiddenFor(m => m.PersonId)
    @Html.EditorFor(m => m.DateReceived)
    <!-- 其他表单元素 -->
    
    <button type="submit">提交</button>
}

额外提醒

  • 检查控制器里有没有其他同名的Create方法,如果有,一定要给它们配置清晰的路由或者HTTP方法约束,避免路由冲突。
  • 如果你的控制器属于某个区域(Area),记得在控制器类上加上[Area("AreaName")]属性,或者在路由模板里包含区域信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:06:46