试图让我的模型验证时间,即结束时间是>开始时间或者如果填充了一个,那么另一个必须填充。
到目前为止,我有:
模型
public int ID { get; set; }
[DataType(DataType.Time, ErrorMessage = "Incorrect format or missing date")]
[DisplayName("MondayStart")]
public DateTime? MondayStart { get; set; }
[DataType(DataType.Time, ErrorMessage = "Incorrect time")]
[DisplayName("MondayEnd")]
[GreaterThanAtt("MondayStart", "MondayEnd", ErrorMessage = "Incorrect format or missing date")]
GreaterThanAtt类
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
namespace OrwellFrontEnd.CompareAtt
{
public class GreaterThanAtt : ValidationAttribute
{
public DateTime _End { get; set; }
public DateTime _Start { get; set; }
public GreaterThanAtt (string Start, string End)
{
_Start = DateTime.ParseExact(Start, "HH:mm", CultureInfo.InvariantCulture); //Convert.ToDateTime(Start);
_End = DateTime.ParseExact(End, "HH:mm", CultureInfo.InvariantCulture); // Convert.ToDateTime(End);
//return DateTime.Compare(this._End, Convert.ToDateTime(_Start)) > 0;
}
public override bool IsValid(object value)
{
if (value != null && DateTime.Compare(_End, _Start) > 0)
{
return true;
}
else
{
return false;
}
}
}
}
查看
<div style="display: table-row;">
<div class="div-label-text" , style="display: table-cell"> @Html.LabelFor(model => model.MondayStart) </div>
<div class="div-EditorFor" , style="display: table-cell"> @Html.EditorFor(model => model.MondayStart, new { htmlAttributes = new { @class = "div-form-control", id = "txtMondayStart" } }) </div>
<div class="div-val-cell" , style="display: table-cell"> @Html.ValidationMessageFor(model => model.MondayStart, "", new { @class = "text-danger" }) </div>
<div class="div-label-text" , style="display: table-cell"> @Html.LabelFor(model => model.MondayEnd) </div>
<div class="div-EditorFor" , style="display: table-cell"> @Html.EditorFor(model => model.MondayEnd, new { htmlAttributes = new { @class = "div-form-control", id = "txtMondayEnd" } }) </div>
<div class="div-val-cell" , style="display: table-cell"> @Html.ValidationMessageFor(model => model.MondayEnd, "", new { @class = "text-danger" }) </div>
</div>
不确定代码是否可行,但现在它已经更改了视图页面,所以当我输入时间时它是一个自由文本..
以前它会显示 - : - 输入时间,但是从结束日期开始,它要求您输入日期时间。