0

我有一个 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 对象中有大量属性(为了便于阅读,我排除了其中的许多属性)。

4

2 回答 2

1

您可以在控制器操作中验证您的模型。

if(!Model.IsValid)
{
  return View(); // ooops didn't work
}
else
{
  return RedirectToAction("Index"); //horray
}

当然你可以放任何你想要的东西,如果你想在你的页面上显示它,则返回 Json 对象。

您还需要ValidateInput(true)像这样添加操作方法的顶部:[HttpPost, ValidateInput(true)]

于 2012-01-03T17:48:42.283 回答
1

我认为您可以为此创建一个自定义 ValidationAttribute。

[DateTimeFormat(ErrorMessage = "Invalid date format.")]
public DateTime? TimestampStart { get; set; }
[DateTimeFormat(ErrorMessage = "Invalid date format.")]
public DateTime? TimestampEnd { get; set; }


[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class DateTimeFormatAttribute : ValidationAttribute
{
    public override bool IsValid(object value) {

        // allow null values
        if (value == null) { return true; }

        // when value is not null, try to convert to a DateTime
        DateTime asDateTime;
        if (DateTime.TryParse(value.ToString(), out asDateTime)) {
            return true; // parsed to datetime successfully
        }
        return false; // value could not be parsed
    }
}
于 2012-01-03T17:50:26.530 回答