尝试使用 Fluent Validation 来确保始终填写日期范围并且结束日期不会出现在开始日期之前。
我已经正确完成了第一部分,并且可以正确触发,但是第二部分似乎无法实现。
我的代码:
public class Report1ToExcelValidator : AbstractValidator<Report1ToExcelViewModel> {
public Report1ToExcelValidator() {
RuleFor(x => x.Report1ToExcelDateFrom)
.NotEmpty().WithMessage("Please provide a valid beginning date for the range.");
RuleFor(x => x.Report1ToExcelDateTo)
.NotEmpty().WithMessage("Please provide a valid end date for the range.")
.GreaterThan(x => x.Report1ToExcelDateFrom.Value).WithMessage("The Date To must be after the Date From");
}
}
一切都被绊倒的地方是.GreaterThan
,它报告了一个错误:
'DateTime' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'DateTime' could be found
我的 DateTime 不可为空,两个 DateTime 都需要内容。当我允许 Intellisense 显示可能的选项时,字段名称之后的任何内容都仅限于 and 之类的内容.Date
,.Hour
这也不起作用。.Value
不存在于该选项列表中,也不存在.HasValue
.
对这一点真的很困惑。
另外,另一个问题:如何对单个页面上存在的多个表单进行单独验证?现在我只有一个表格,但是表格的模型是直接带进来的。我似乎无法弄清楚如何抽象出表单的模型,以便我可以在页面上拥有多个模型。没有数据被引入。
现在我刚刚尝试将模型更改为:
public class ReportViewModel {
public Report1ToExcelViewModel Report1ToExcelViewModel { get; set; }
}
[Validator(typeof(Report1ToExcelValidator))]
public class Report1ToExcelViewModel {
public Guid? Report1ToExcelRegion { get; set; }
public DateTime Report1ToExcelDateFrom { get; set; }
public DateTime Report1ToExcelDateTo { get; set; }
}
使用页面引用@model CCS.Models.ReportViewModel
而不是,@model CCS.Models.Report1ToExcelViewModel
但我似乎无法让页面拉入 Report1ToExcelViewModel 以便识别表单字段。现在他们出错了,因为'ReportViewModel' does not contain a definition for [fieldname]
即使我像上面那样Report1ToExcelViewModel
直接带入。ReportViewModel