您不能將驗證屬性應用於複雜屬性並獲取客戶端驗證,因爲您沒有(也不能)爲複雜對象(僅限對象的屬性)創建窗體控件。你需要創建一個視圖模型來表示要在視圖中顯示(注意是空的屬性)
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」)]'? –