How to check the number of items in a list in mvc model

I am writing an online evaluation form. In this form, the user must select a minimum of 3 and a maximum of 7 people who will give them a rating. I have a form where the user adds evaluators and I display a list under this form. Once the user has finished adding evaluators, click the self-assessment button to fill in their own assessment of themselves.

What I want to do is to check if the number of evaluators is really in the right range before the user leaves the page.

The model is similar to this

public class AssessorsViewModel
{
    List<Assessor> Assessors { get; set; }
}

public class Assessor
{
    string Email { get; set; }
    string Name { get; set; }
}

I have verification attributes for the Assessor class, so every time a user adds an expert, I can check this, but I can’t figure out how to check the account in the list of evaluators.

I am using ASP.net MVC.

Thanks in advance

+4
3

:

public ActionResult TheAction(AssessorsViewModel model)
{
    if (model.Assessors == null
        || model.Assessors.Count < 3
        || model.Assessors.Count > 7)
    {
        ModelState.AddModelError("Assessors", "Please enter note less than 3 and not more than 7 assessors.");
        return View(model);
    }
    ...
}

- . , ( , ).

+1

ValidationAttribute :

public class LimitCountAttribute : ValidationAttribute
{
    private readonly int _min;
    private readonly int _max;

    public LimitCountAttribute(int min, int max) {
        _min = min;
        _max = max;
    }

    public override bool IsValid(object value) {
        var list = value as IList;
        if (list == null)
            return false;

        if (list.Count < _min || list.Count > _max)
            return false;

        return true;
    }
}

:

public class AssessorsViewModel
{
    [LimitCount(3, 7, ErrorMessage = "whatever"]
    List<Assessor> Assessors { get; set; }
}
+7
+1

Source: https://habr.com/ru/post/1531809/


All Articles