检查模型的真值

时间:2019-01-04 16:05:51

标签: asp.net-mvc model

我有一个带有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");
    }

1 个答案:

答案 0 :(得分:0)

将您的布尔成员添加到列表中

使用linq检查真实布尔成员的计数是否大于或等于3 reteurn true

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