【问题标题】:ASP.NET Core POST hitting the wrong actionASP.NET Core POST 操作错误
【发布时间】:2019-05-07 17:00:46
【问题描述】:

我有一个具有以下操作的控制器

[HttpPost("training/create", Name="Create")]
public async Task<IActionResult> Create(CreateTrainingCommand command){
    // doing stuff ...
}

[HttpGet("training/createblankform", Name="CreateBlankForm")]
public async Task<IActionResult> CreateBlankForm(CreateBlankFormQuery command){
    // doing stuff ...
}

[HttpPost("training/createblankform", Name="CreateBlankForm")]
public async Task<IActionResult> CreateBlankForm(CreateBlankFormCommand command){
    // doing stuff ...
}

在我的 StartUp.cs 文件中,我使用 app.UseMvcWithDefaultRoute() and I have loaded a View that is loaded using theCreateBlankFormGET` 操作。

视图包含一个应该提交给CreateBlankForm POST 操作的表单,但Create POST 操作却被触发了。

我尝试了几种不同的方式来配置表单;

<form class="form-horizontal" role="form" contenteditable="" asp-controller="Training" asp-action="CreateBlankForm" method="post">
...
        <input id="submit" type="button" value="Create" />
</form>

<form class="form-horizontal" role="form" contenteditable="" asp-route="CreateBlankTrainingForm" method="post">
...
        <input id="submit" type="button" value="Create" />
</form>

<form class="form-horizontal" role="form" action="/training/createblankform" method="post">
...
        <input id="submit" type="button" value="Create" />
</form>

但所有这些仍然会触发 CreateBlankForm POST 操作。为什么这会打错控制器?

【问题讨论】:

  • 带有 type="submit" 的 html 按钮将提交表单并发布到CreateBlankForm post action ,您是否有任何由提交按钮触发的javascript函数?
  • @NanYu - 是的,这就是原因 - 创建了一个 JavaScript“提交”处理程序。如果您想提交答案,我会标记为已接受。
  • 好的,我会回复的,谢谢

标签: asp.net-core routing


【解决方案1】:

是否有任何 JavaScript 事件正在处理 submit 表单操作?

【讨论】:

  • 是的,链接文件中有一个通用的 JavaScript 事件处理程序 ($("#submit").click(function () {..})。
【解决方案2】:

尝试改变

    <input id="submit" type="button" value="Create" />

    <input id="submit" type="submit" value="Create" />

还有你指定的错误动作名称 应该是

action="createblankform"

不是

action="/training/createblankform"

如果您有任何问题,请告诉我

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2021-02-25
    • 2020-10-12
    • 2020-12-23
    • 2019-09-07
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多