简体   繁体   中英

Is it possible to bypass Data Annotations from a class at run time?

The View will display either a search on Name OR Date. The problem is that the ValidationSummary (in accordance to the class) requires both values to be entered, and will add an error for the field/property that is not been displayed. Is there any way to prevent it to require the Date when the search is only prompting for the Name ? Like disabling the related Data Annotation?

NOTE: For simplicity, the code has been shortened and it is for ilustration only. Please, do not vote it down if u find a missing ";" or similar.

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>

Using something like a RequiredIf annotation, as Daniel suggests in the comments above, is probably the most elegant solution, but just for completeness, here's other options.

First, you can merely remove the error. Something along the lines of:

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

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

Basically, whichever type of search is done, you just clear the errors for the other field.

Second, you can manually validate instead of relying on the annotation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM