5

I am trying to implmenet a file uploader that can take various amounts of files. The files input elemnts are all named the same so produce a list of files that MVC3 happily binds to.

So in my controller I have have

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

This gets all the files it should. However all empty form file input elements are adding a null. This is stopping my basic non empty List validation in the controller from working as I want.

The validation is 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 change the validation to generically count only non null elements?

GraemeMiller
  • 11,973
  • 8
  • 57
  • 111
  • You mean your list is not empty but contains null elements ? You can do `return list.Count(i => i != null)` – Didier Ghys Dec 08 '11 at 10:22
  • Doesn't work. I get Error 'System.Collections.IList' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'System.Collections.IList' – GraemeMiller Dec 08 '11 at 10:36
  • You probably have to reference `System.Linq` – Didier Ghys Dec 08 '11 at 10:37
  • Yeah this was what I tried first. Linq is referenced. I think the issue is that it is generic. – GraemeMiller Dec 08 '11 at 10:38
  • Indeed, extension methods are on the List<> class. Well you can either change the type to a List<> and use linq or loop and count yourself the non-null elements. – Didier Ghys Dec 08 '11 at 10:50

1 Answers1

3

If you only want to count non-null objects you can use LINQ with an IList by using:

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

Alternatively you can just loop and count each non-null object.

int count = 0;
foreach (var item in list)
{
    if (item != null)
        count++;
}
João Angelo
  • 56,552
  • 12
  • 145
  • 147