如何验证列表中的大于零,与MVC非null元素属性? [英] How do I validate list has greater than zero non null elements with MVC Attribute?

查看:295
本文介绍了如何验证列表中的大于零,与MVC非null元素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想implmenet,可以采取不同数量的文件的文件上传。这些文件输入elemnts都命名一样的,所以产生的文件列表,MVC3愉快地结合。

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.

所以在我的控制器我有

公共虚拟的ViewResult UploadReceive(IEnumerable的< HttpPostedFileBase>文件){

这得到它应该的所有文件。但是,所有的空表格文件输入元素添加一个空。这是从工作,我想停在控制器我基本不空List验证。

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.

该验证如下:

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;
    }
}

任何想法我如何验证改为一般只计算非null元素?

Any idea how I change the validation to generically count only non null elements?

推荐答案

如果您只想计算非空的对象,你可以使用LINQ与的IList 使用:

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++;
}

这篇关于如何验证列表中的大于零,与MVC非null元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆