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