我有一个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控制器是否有一些特殊规则?谢谢
答案 0 :(得分:2)
尝试使用[FromForm]
属性:
public Departure SubmitDestination([FromForm]Departure departure)
这指示模型绑定程序从x-www-urlencoded
读取数据
答案 1 :(得分:0)
正如@Nkosi在评论中指出的那样,API控制器是对Json的期望,但是我试图从表单(不是Json)中传递数据。我没有找到解决方案,但这就是问题