How to check a list has more than zero null elements with MVC attribute?

I am trying to implement a file downloader that can accept different numbers of files. Input elements for file input have the same name, so create a list of files that MVC3 happily associates with.

So in my controller I have

public virtual ViewResult UploadReceive(IEnumerable<HttpPostedFileBase> Files ){

This gets all the files it needs. However, all empty form file input elements add zero. This stops my basic non-empty list check in the controller from working as I want.

Verification is performed below:

 public class EnsureMinimumElementsAttribute : ValidationAttribute { private readonly int _minElements; public EnsureMinimumElementsAttribute(int minElements) { _minElements = minElements; } public override bool IsValid(object value) { var list = value as IList; if (list != null) { return list.Count >= _minElements; } return false; } } 

Any idea how I can change the validation to generally only count non-zero elements?

+4
source share
1 answer

If you only want to count nonzero objects, you can use LINQ with IList using:

 list.Cast<object>().Count(o => o != null) 

Alternatively, you can simply quote and count each nonzero object.

 int count = 0; foreach (var item in list) { if (item != null) count++; } 
+3
source

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


All Articles