我有一个模型,主要是布尔属性,有5个附加字符串和一个int。我的问题是,有一种方法可以检查这个模型上是否至少有3个真值。我知道我可以遍历这些值,但是我的属性名目前是不同的名称,而不是checkbox1、checkbox2等等。如果可能的话,我想保持名字的唯一性。我甚至不确定我想要的是不是可能。
型号:
namespace FacilitesPledgeForm.Models {
public class FacilitiesPledge
{
public bool LightsOff {get; set;}
public bool PowerDown {get; set;}
public bool PrintLess {get; set;}
public bool Stairs {get; set;}
public string test1 {get; set;}
public string test1 {get; set;}
public string test2 {get; set;}
public string test3 {get; set;}
public string test4 {get; set;}
public string test5 {get; set;}
public int num {get; set;}
}
} 控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Submit_PledgeForm(FacilitiesPledge facilitiesPledge)
{
//I want to loop here for at least 3 true values and if there isn't add an error to the model to make it invalid
if (!ModelState.IsValid)
{
return View("Index", facilitiesPledge);
}
facilitiesPledge.UserName = User.Identity.Name;
facilitiesPledge.Email = User.Identity.Name.ToUpper();
facilitiesPledge.Year = DateTime.Now.Year;
new PledgeFormStore().InsertPledgeAcceptance(facilitiesPledge);
return View("SuccessfulSubmission");
}发布于 2019-01-05 03:20:44
将布尔成员添加到列表中
如果真布尔成员的计数大于或等于3,则使用linq检查
public class FacilitiesPledge
{
public bool LightsOff { get; set; }
public bool PowerDown { get; set; }
public bool PrintLess { get; set; }
public bool Stairs { get; set; }
public string test1 { get; set; }
public string test2 { get; set; }
public string test3 { get; set; }
public string test4 { get; set; }
public string test5 { get; set; }
public int num { get; set; }
public bool IsValid()
{
//add your boolean members
List<bool> items = new List<bool> { LightsOff, PowerDown, PrintLess, Stairs };
//if count of true Boolean member more than or equeal to 3 reteurn true
bool isValid = items.Count(x => x == true) >= 3;
return isValid;
}
}https://stackoverflow.com/questions/54042405
复制相似问题