表单无效时 400 错误请求
400 bad request when form is invalid
我为这个问题苦苦挣扎了两天,我对 .net core 有点陌生。我收到 400 个错误请求,并且仅当我 post 无效表单(必填字段为空)时请求才不会触发我的操作,这正常吗?如果是这样,为什么我的错误验证消息没有显示?!
如果不正常,是否与中间件有关?
这是我的代码
我的行动:
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Save([FromForm] myModel model)
{
string message = "";
if (ModelState.IsValid)
{
message = "product " + model.DecisionDate + " created successfully";
}
else
{
return View(model);
}
return Content(message);
}
我的表格:
<form id="msform" class="form-horizontal" data-ajax="true" data-ajax-method="post" data-ajax-url="Save">
@Html.ValidationMessageFor(model => model.DecisionDate)
<input type="datetime-local" asp-for="DecisionDate" class="form-control text-right" name="DecisionDate" placeholder="Email">
<textarea class="form-control" name="Notes" rows="3"></textarea>
<input type="submit" name="next" class="next action-button" value="save"/>
</form>
我的模特:
public class myModel
{
[Required(ErrorMessage = "Decision date cannot be empty")]
public DateTime? DecisionDate { get; set; }
public string Notes { get; set; }
}
最后我找到了解决方案以防有人遇到同样的问题,这是一个中间件问题,我添加了这个并且它工作正常:
services.AddControllersWithViews().ConfigureApiBehaviorOptions(options => options.SuppressModelStateInvalidFilter = true)
我为这个问题苦苦挣扎了两天,我对 .net core 有点陌生。我收到 400 个错误请求,并且仅当我 post 无效表单(必填字段为空)时请求才不会触发我的操作,这正常吗?如果是这样,为什么我的错误验证消息没有显示?! 如果不正常,是否与中间件有关? 这是我的代码
我的行动:
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Save([FromForm] myModel model)
{
string message = "";
if (ModelState.IsValid)
{
message = "product " + model.DecisionDate + " created successfully";
}
else
{
return View(model);
}
return Content(message);
}
我的表格:
<form id="msform" class="form-horizontal" data-ajax="true" data-ajax-method="post" data-ajax-url="Save">
@Html.ValidationMessageFor(model => model.DecisionDate)
<input type="datetime-local" asp-for="DecisionDate" class="form-control text-right" name="DecisionDate" placeholder="Email">
<textarea class="form-control" name="Notes" rows="3"></textarea>
<input type="submit" name="next" class="next action-button" value="save"/>
</form>
我的模特:
public class myModel
{
[Required(ErrorMessage = "Decision date cannot be empty")]
public DateTime? DecisionDate { get; set; }
public string Notes { get; set; }
}
最后我找到了解决方案以防有人遇到同样的问题,这是一个中间件问题,我添加了这个并且它工作正常:
services.AddControllersWithViews().ConfigureApiBehaviorOptions(options => options.SuppressModelStateInvalidFilter = true)