2

我已将一个 Asp.Net 项目移植到 .Net Core,并注意到我的 POST 端点不再工作。

    [HttpGet, Route("Concert/Add/{eventId:int?}")]
            public ActionResult Add(int eventId)
            {
//This works
    }

     [HttpPost]
            [Route("Concert/Add")]
            public IActionResult Add(EntryViewModel entryViewModel)
            {
//This action is never reached. I get a 404 Not found in browser
    }

在我看来,我有以下形式:

  @using (Html.BeginForm("Add", "Concert", new { eventId = Model.EventId }, FormMethod.Post, null, new { @class = "center-block entryform AddEntry" }))
    {
  <div class="form-group">
            @Html.LabelFor(model => model.Forename, new { @class = "control-label entryLabel" })
            <div class="">
                @Html.TextBoxFor(model => model.Forename, new { @class = "form-control" })
            </div>
        </div>
    }

我的 StartUp.cs Configure() 看起来像这样:

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "Events",
                    template: "{controller=Home}/{action=Index}/{eventId?}");
            });

如果我将我的 Post 端点路由更改为 [Route("Customer/Add/{entryViewModel})"] 那么它导航到该操作,但模型为空。我是否缺少其他配置?

4

2 回答 2

1

看起来您的路线上有错字,端点不会被击中。

[Route("Convert/Add/{entryViewModel}")]

它应该是

[Route("Concert/Add/{entryViewModel}")]

我还将删除new { eventId = Model.EventId }中的@Html.BeginForm以确保将EntryViewModel其序列化并正确传递给 HTTP 端点。

另外,由于您没有提供您的EntryViewModel类,我将确保它具有关联的正确 getter 和 setter,以便模型绑定起作用,例如:

public class EntryViewModel
{
   [Required]
   [DisplayName(Name="Forename")]
   public string Forename { get; set; }
}

在您的表单中,您可以使用ASP.NET Core Tag Helpers。

<form asp-controller="Concert" asp-action="Add" method="post">
    Forename:  <input asp-for="Forename" /> 
    <br />
    <button type="submit">Submit</button>
</form>
于 2018-12-14T10:58:33.473 回答
0

使用 [FromBody] 作为参数

 [HttpPost]
 [Route("Concert/Add")]
 public IActionResult Add([FromForm]EntryViewModel entryViewModel)
 {

 }

我还看到:

new { eventId = Model.EventId }

所以,这样更好

 [HttpPost]
 [Route("Concert/Add/{eventId:int}")]
 public IActionResult Add(int eventId,[FromForm]EntryViewModel entryViewModel)
 {

 }
于 2018-12-14T11:10:57.760 回答