首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查模型中的真值

检查模型中的真值
EN

Stack Overflow用户
提问于 2019-01-05 00:05:51
回答 1查看 60关注 0票数 0

我有一个模型,主要是布尔属性,有5个附加字符串和一个int。我的问题是,有一种方法可以检查这个模型上是否至少有3个真值。我知道我可以遍历这些值,但是我的属性名目前是不同的名称,而不是checkbox1、checkbox2等等。如果可能的话,我想保持名字的唯一性。我甚至不确定我想要的是不是可能。

型号:

代码语言:javascript
复制
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;}
   }

}    

控制器:

代码语言:javascript
复制
    [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");
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-05 03:20:44

将布尔成员添加到列表中

如果真布尔成员的计数大于或等于3,则使用linq检查

代码语言:javascript
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54042405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档