我有一个 HttpPost 控制器操作,它采用简单的形式 DTO 对象。
[HttpPost]
public ViewResult Index(ResultQueryForm queryForm)
{
...
}
public class ResultQueryForm
{
public DateTime? TimestampStart { get; set; }
public DateTime? TimestampEnd { get; set; }
public string Name { get; set; }
}
DTO 对象具有用于创建范围的可为空的日期时间字段。之所以设置为nullable,是因为模型绑定的表单是查询表单,用户不必在表单中输入日期值。
我遇到的问题是,如果用户输入的日期无效,我希望 MVC 默认模型绑定提供错误消息。如果我有一个需要 DateTime 的控制器操作,这会完美地发生吗?类型作为参数,但是因为我传递了一个包含 DateTime 的 DTO?键入模型绑定似乎只是设置了 DateTime?变量为空。这会导致意想不到的结果。
笔记:
[HttpPost]
public ViewResult Index(DateTime? startDate)
{
// If the user enters an invalid date, the controller action won't even be run because the MVC model binding will fail and return an error message to the user
}
如果不能绑定 DateTime,是否有告诉 MVC 模型绑定“失败”?为表单 DTO 对象赋值,而不仅仅是将其设置为 null?有没有更好的办法?将每个单独的表单输入传递给控制器是不可行的,因为 form/dto 对象中有大量属性(为了便于阅读,我排除了其中的许多属性)。