您不能将验证属性应用于复杂属性并获取客户端验证,因为您没有(也不能)为复杂对象(仅限对象的属性)创建窗体控件。你需要创建一个视图模型来表示要在视图中显示(注意是空的属性)
public class DayScheduleVM
{
public bool IsRequired { get; set; } // this will be used for conditional validation
[RequiredIf("IsRequired", ErrorMessage = "Please enter the start time")]
public TimeSpan? StartTime { get; set; }
[RequiredIf("IsRequired", ErrorMessage = "Please enter the end time")]
public TimeSpan? EndTime { get; set; }
[RequiredIf("IsRequired", ErrorMessage = "Please enter the interval")]
public TimeSpan? Interval { get; set; }
}
public WeekScheduleVM
{
public DayScheduleVM Sunday { get; set; }
public DayScheduleVM Monday { get; set; }
....
}
什么,并在视图
@model WeekScheduleVM
....
@using (Html.BeginForm())
{
<table>
....
<tbody>
<tr>
<td>@Html.DisplayNameFor(m => m.Sunday)</td>
<td>@Html.CheckBoxFor(m => Sunday.IsRequired)</td>
<td>
@Html.TextBoxFor(m => Sunday.StartTime)
@Html.ValidationMessageFor(m => Sunday.StartTime)
</td>
.... // ditto for EndTime and Interval
</tr>
<tr>
.... // ditto for Monday,Tuesday etc
</tr>
这时如果复选框被选中,你将得到一个客户端(和服务器端)的错误,它关联的StartTime
,EndTime
和Interval
属性未填写(其不清楚Interval
的用途 - 名称暗示其计算值基于StartTime
和EndTime
,因此可能不需要在视图中)
您可以在此进一步简化并通过添加DayOfWeek
枚举属性显著减少代码量在视图中DayScheduleVM
public DayOfWeek Day { get; set; }
,这样在你的GET方法,您可以使用
List<DayScheduleVM> model = new List<DayScheduleVM>();
foreach (var day in Enum.GetValues(typeof(DayOfWeek)))
{
days.Add(new DayScheduleVM { Day = (DayOfWeek)day });
}
return View(model);
并在视图中
@model List<DayScheduleVM>
....
@using (Html.BeginForm())
{
<table>
....
<tbody>
@for(int i = 0; i < Model.Count; i++)
{
<tr>
<td>@Html.DisplayFor(m => m[i].Day)</td>
<td>@Html.CheckBoxFor(m => m[i].IsRequired)</td>
<td>
@Html.TextboxFor(m => m[i].StartTime)
@Html.ValidationMessageFor(m => m[i].StartTime)
</td>
.... // ditto for `EndTime` and `Interval`
</tr>
}
</tbody>
</table>
<input type="submit" ... />
}
此验证是否只需要进行服务器端验证?侧? –
我不认为'FoolProof'中的'RequiredIf'适用于复杂模型,而且对于最近的一个,您的情况下的注释也表示'workDay'注释。尝试将'workDay'属性添加到'Week'类中,然后在模型绑定中处理细节。 – Hadee
'[必填项(“(星期二)”]'没有意义。格式为'[RequiredIf(“someOtherProperty”,“ValueOfOtherProperty”)]''也许你的意思是'[RequiredIfTrue(“tuesday”)]'? –