Search code examples
asp.net-mvcvalidationrazorzero

Razor/MVC Empty List Validation


I have a SelectList of IDs that the user can choose zero-many items into a List. By default the validation logic appears to require at least one element to be selected. I have tried using the annotation [MinLength(0)] as various documentation implies that it applies to not only strings but collections/lists.

The obvious answer to my question is to just disable validation of the property.

The slightly less obvious answer is to write my own custom ValidationAttribute which seems to be more effort than warranted.

I am looking if there is another simple way.

My ViewModel property:

        public List<int> DiverIDList { get; } = new List<int>();

My CSHTML:

@{
    var DiverSL = (SelectList)ViewData["DiverSL"];
}
<div class="form-group">
    <label asp-for="DiverIDList" class="control-label"></label>
    <select asp-for="DiverIDList" class="form-control"
            asp-items="@DiverSL" size="8">
        <option value="">-- Select Divers --</option>
    </select>
    <span asp-validation-for="DiverIDList" class="text-danger" />
</div>

Solution

  • In order to better understand the problem, I decided to create a custom ValidationAttribute derived from RequiredAttribute. Although I was able to verify that my new validation attribute's IsValid was getting called, there were still cases when the ICollection.Count == 0 was causing the custom validation to not be called and the server ModelState contained an error. Something in the framework is bypassing attribute based validation in this case.

    Because I have Nullable enabled, I tried the different combinations of making the List nullable or not. No change in behavior.

    The only viable solution appears to be disabling validation for that property. This requires two steps:

    1. In the OnPost method before calling ModelState.IsValid, insert a call to ModelState.Remove("ModelDiver.DiverIDList");
    2. In the CSHTML, add data-val="false" to the <select> tag.