ASP.NET Core MVC-从表单到控制器操作的无效输入

时间:2018-11-23 16:22:03

标签: c# entity-framework api controller asp.net-core-mvc

我有一个HomeController,它返回一个视图...在我的视图中,我提交一个表单,该表单由ServicesController和操作SubmitDestination处理。 (错误/问题在底部列出)

HomeController

public class HomeController : Controller
{
    [ActionName("Index")]
    public IActionResult Index()
    {
        return View();
    }
}

查看

@model ScheduleService.Models.Departure

<form asp-controller="Services" asp-action="SubmitDestination" method="post">
    Departure time: <input asp-for="DepartureTime"/>
    Number: <input asp-for="Number"/>
    Destination<input asp-for="Destination"/>
    <button type="submit">Submit</button>
</form>

ServicesController

[Route("api/[controller]")]
[ApiController]
public class ServicesController : ControllerBase
{
    [HttpPost]
    public Departure SubmitDestination(Departure departure)
    {
        Departure _departure = new Departure
        {
            DepartureTime = departure.DepartureTime,
            Number = departure.Number,
            Destination = departure.Destination
        };

        _db.DepartureDB.Add(_departure);
        _db.SaveChanges();

        return _db.DepartureDB.LastOrDefault();
    }
}

问题:提交表单时,这是浏览器中返回的响应:

{"":["The input was not valid."]}

任何人都可以发现为什么我的输入无效吗? API控制器是否有一些特殊规则?谢谢

2 个答案:

答案 0 :(得分:2)

尝试使用[FromForm]属性:

public Departure SubmitDestination([FromForm]Departure departure)

这指示模型绑定程序从x-www-urlencoded读取数据

答案 1 :(得分:0)

正如@Nkosi在评论中指出的那样,API控制器是对Json的期望,但是我试图从表单(不是Json)中传递数据。我没有找到解决方案,但这就是问题