2016-02-03 50 views
0

視圖將顯示名稱或日期的搜索。問題在於ValidationSummary(根據類)需要輸入兩個值,並且會爲未顯示的字段/屬性添加錯誤。有沒有什麼辦法可以防止它在搜索只是提示姓名時需要日期?像禁用相關的數據註解一樣?是否可以在運行時繞過類的數據註釋?

注意:爲簡單起見,代碼已縮短,僅用於示例。請不要投票,如果你找不到「;」或類似的。

public class CustomSearch 
{ 
    [Required(ErrorMessage = "The text must be filled in.")] 
    public string SearchTextValue { get; set; } 

    [Required(ErrorMessage = "The Date must be selected.")] 
    public string SearchDateValue { get; set; } 
} 

<div> 
    <div> 
     @if (Model.SearchValidationSummary) { @Html.ValidationSummary(false) } 
    <div> 

    @using (Html.BeginForm("", "", FormMethod.Post)) 
    { 
     if (Model.SearchText) { @Html.TextBoxFor(m => m.SearchTextValue) } 
     else if (Model.SearchDate) { @Html.DateEditFor(m => m.SearchDateValue) } 
    } 
</div> 
+0

,如果你找htat有圖案的'requiredif'。 –

回答

0

使用像一個RequiredIf註釋,如丹尼爾提出的上述意見,可能是最優雅的解決方案,但只是爲了完整性,這裏的其他選項。

首先,您只能刪除錯誤。沿線的一些東西:

if (searchType = "text") 
{ 
    ModelState["SearchDateValue"].Errors.Clear(); 
} 

if (searchType = "date") 
{ 
    ModelState["SearchTextValue"].Errors.Clear(); 
} 

基本上,無論哪種類型的搜索完成,您只需清除其他字段的錯誤。

其次,你可以手動驗證,而不是依靠註解:

if (searchType == "text" && String.IsNullOrWhiteSpace(model.SearchTextValue)) 
{ 
    ModelState.AddModelError("SearchTextValue", "The text must be filled in."); 
} 
+0

我發現你的解決方案更具可擴展性,因爲有些情況下根據模型在代碼中的使用方式來定製驗證可能會更好。 –

相關問題