在我的 MVC4 应用程序中。我有一个名为的视图模型SixweekRangeViewModel
public class SixweekViewModel: IValidatableObject
{
public int Position { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (StartDate.HasValue || EndDate.HasValue)
{
if (!StartDate.HasValue || !EndDate.HasValue)
{
yield return new ValidationResult("*");
// new string[] { "StartDate", "FinalDate" }
}
}
}
}
这是我显示项目的视图
@model List<Contoso.MvcApplication.ViewModels.Assignments.SixweekViewModel>
<h2>Configure Sixweeks</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Configure Sixweeks</legend>
@for (int i = 0; i < Model.Count; i++) {
<div>
@Html.HiddenFor(model => model[i].Position)
@Html.TextBoxFor(model => model[i].StartDate, "{0:d/MMM/yyyy}", new { @class = "from" + i })
@Html.TextBoxFor(model => Model[i].EndDate, "{0:d/MMM/yyyy}", new { @class = "to" + i })
</div>
}
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
当我按保存时,调试器将validationResult 作为错误获取。但永远不要在视图中显示错误消息。
我认为这IValidatableObject
应该在List<T>
而不是T
对象中实现,但这只是一个想法。我想念什么人?