Asp.net核心迁移,发布操作不再起作用

时间:2018-12-14 10:55:13

标签: c# razor asp.net-core-mvc asp.net-core-2.0

我已将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})”],则它将导航至该操作,但模型为null。我是否缺少其他配置?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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)
 {

 }