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

ASP.NET Core 6 MVC:带参数的Create GET正常,POST方法未触发

问题:ASP.NET Core 6 MVC中Create表单提交未触发POST方法

在ASP.NET Core 6 MVC的Create操作中,GET方法接收可选参数idEnt。访问MyController/Create/5时视图正常显示,客户端验证也能工作,但提交表单时控制器的POST方法未触发,仅重载视图。

控制器代码

[Route("MyController/Create/{idEnt:int?}")]
public async Task<IActionResult> Create(int? idEnt) 
{
    MyEntity ent = db.Find(idEnt);

    var mod = new Mod() { idEnt = idEnt };

    return View(mod);
}

[HttpPost]
[ValidateAntiForgeryToken]
[WebTrail(AuditLevel = 3)]
public async Task<IActionResult> Create(Mod mod) 
{
    if (ModelState.IsValid) 
    {
        _db.Add(mod);
        await _db.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(mod);
}

视图代码

@model My.Namespace.Mod
<div>
    <form asp-action="Create">
        <input type="hidden" asp-for="Id" />
        <input type="hidden" asp-for="IdEnt" />

        <label asp-for="someField" class="control-label"></label>
        <input asp-for="someField" class="form-control" />
        <span asp-validation-for="someField" class="text-danger"></span>

        <!-- more form inputs etc here -->

        <input type="submit" value="Save" class="btn btn-primary" />
    </form>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

模型代码

public class Mod 
{
    public int Id { get; set; }

    [ForeignKey("Ent")]
    public int? IdEnt { get; set; }

    [DisplayFormat(DataFormatString = "{0}€", NullDisplayText = "---")]
    [Column(TypeName = "decimal(15,2)")]
    public decimal? SomeField { get; set; }

    public virtual Ent Ent { get; set; }
}

问题原因

第一个Create方法仅标记了[Route]属性,未指定[HttpGet],在ASP.NET Core中,未指定HTTP动词的带路由属性的方法会接受所有HTTP方法的请求(包括POST)。当表单提交时,请求会匹配到这个方法,而非定义的[HttpPost]版本,因此执行的是GET逻辑,返回视图导致页面重载。

解决方案

  1. 给第一个Create方法添加[HttpGet]属性,明确它仅处理GET请求:
[HttpGet]
[Route("MyController/Create/{idEnt:int?}")]
public async Task<IActionResult> Create(int? idEnt) 
{
    // 原有代码不变
}
  1. (可选)如果需要在POST请求中保留idEnt路由参数,可在表单中指定路由参数:
<form asp-action="Create" asp-route-idEnt="@Model.IdEnt">
    <!-- 表单内容不变 -->
</form>

调整后,POST请求会正确匹配到带[HttpPost]的Create方法,执行提交逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:55:10