ViewModel validation for a List

前端 未结 7 1639
梦谈多话
梦谈多话 2020-11-28 02:54

I have the following viewmodel definition

public class AccessRequestViewModel
{
    public Request Request { get; private set; }
    public SelectList Buildi         


        
7条回答
  •  日久生厌
    2020-11-28 03:05

    Another possible way to handle the count validations for view model object's collection members, is to have a calculated property returning the collection or list count. A RangeAttribute can then be applied like in the code below to enforce count validation:

    [Range(minimum: 1, maximum: Int32.MaxValue, ErrorMessage = "At least one item needs to be selected")]
    public int ItemCount
    {
        get
        {
            return Items != null ? Items.Length : 0;
        }
    }
    

    In the code above, ItemCount is an example calculated property on a view model being validated, and Items is an example member collection property whose count is being checked. In this example, at least one item is enforced on the collection member and the maximum limit is the maximum value an integer can take, which is, for most of the practical purposes, unbounded. The error message on validation failure can also be set through the RangeAttribute's ErrorMessage member in the example above.

提交回复
热议问题