简体   繁体   English

如何检查是否已填充ViewModel的任何属性

[英]How to check if any property of a ViewModel has been filled

I have a ViewModel which contains properties that can optionally be filled from the user of my web application (eg first name, last name, e-mail, date of birth etc). 我有一个ViewModel,其中包含可以选择由我的Web应用程序用户填充的属性(例如,名字,姓氏,电子邮件,出生日期等)。 These properties include several types like string, bool int, decimal, double, DateTime. 这些属性包括几种类型,例如字符串,布尔整数,小数,双精度,日期时间。 All these types can be both nullable and non-nullable in the ViewModel. 所有这些类型在ViewModel中都可以为可空和不可空。

If at least 1 of these properties has been filled in, then I have to create a database record. 如果至少已填写这些属性中的1个,那么我必须创建一个数据库记录。 Do you have any idea for a way to check if any of these optional values has been filled? 您是否有办法检查这些可选值是否已填写?

By convention, primitive data types are required. 按照约定,原始数据类型是必需的。 You can make the properties nullable which are primitive like int, double, DateTime vs. Then: 您可以使属性为null,这些属性可以是原始的,例如int,double,DateTime vs.然后:

PropertyInfo[] infos = yourObjectInstance.GetType().GetProperties();            
int count = 0;

for(int i = 0; i < infos.Length; i++)
{
    if(infos[i].PropertyType == typeof(string))
    {
        string stringValue = infos[i].GetValue(yourObjectInstance).ToString().Trim();

        if(!string.IsNullOrEmpty(body))
        {
            count++;
        }

        continue;
    }

    if(infos[i].GetValue(yourObjectInstance) != null)
    {                    
        count++;
    }
}

if(count == 0)
{
    // Handle error
}

// Create record

You can implement this code, pass your viewmodel, then count how much fields are not null, if the return value>0 , then you can implement your Db work. 您可以实现此代码,传递您的viewmodel,然后计算有多少字段不为null,如果返回值> 0 ,则可以实现您的Db工作。

public int MethodToCheckNotNull(ViewModel obj)
{
        int i = 0;
        PropertyInfo[] properties = typeof(obj).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            if (property.GetValue(obj) != null)
            {
                i++;
            }
        }
        return i;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM