Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对复选框组进行自定义验证_C#_Asp.net Mvc 2 - Fatal编程技术网

C# 对复选框组进行自定义验证

C# 对复选框组进行自定义验证,c#,asp.net-mvc-2,C#,Asp.net Mvc 2,我试图了解如何验证一组复选框 我的模型: [MinSelected(MinSelected = 1)] public IList<CheckList> MealsServed { get; set; } 有人能帮我解决这个问题吗?您可以重写该方法,并确保集合中至少包含MinSelected项,且IsChecked等于true(我想您的检查表类具有IsChecked属性): public类MinSelectedAttribute:ValidationAttribute { 公共整数{

我试图了解如何验证一组复选框

我的模型:

[MinSelected(MinSelected = 1)]
public IList<CheckList> MealsServed { get; set; }
有人能帮我解决这个问题吗?

您可以重写该方法,并确保集合中至少包含
MinSelected
项,且
IsChecked
等于
true
(我想您的
检查表
类具有
IsChecked
属性):

public类MinSelectedAttribute:ValidationAttribute
{
公共整数{get;set;}
公共覆盖布尔值有效(对象值)
{
var instance=作为IList的值;
if(实例!=null)
{
//确保你至少有一天的时间
//IsChecked值在IList内等于true
//集合,以使模型有效
返回instance.Where(x=>x.IsChecked).Count()>=MinSelected;
}
返回base.IsValid(值);
}
}
#region Validators

public class MinSelectedAttribute : ValidationAttribute
{
    public int MinSelected { get; set; }

    // what do I need to do here?
}
public class MinSelectedAttribute : ValidationAttribute
{
    public int MinSelected { get; set; }

    public override bool IsValid(object value)
    {
        var instance = value as IList<CheckList>;
        if (instance != null)
        {
            // make sure that you have at least MinSelected
            // IsChecked values equal to true inside the IList<CheckList>
            // collection for the model to be valid
            return instance.Where(x => x.IsChecked).Count() >= MinSelected;
        }
        return base.IsValid(value);
    }
}