从视图模型获取属性

本文关键字:属性 获取 模型 视图 | 更新日期: 2023-09-27 18:36:52

我有一种方法可以将类属性推送到 NameValuCollection 中

private NameValueCollection ObjectToCollection(object objects)
{
    NameValueCollection parameter = new NameValueCollection();

    Type type = objects.GetType();
    PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance |
                                                    BindingFlags.DeclaredOnly |
                                                    BindingFlags.Public);
    foreach (PropertyInfo property in properties)
    {
        if (property.GetValue(objects, null) == null)
        {
            parameter.Add(property.Name.ToString(), "");
        }
        else
        {
            if (property.GetValue(objects, null).ToString() != "removeProp")
            {
                parameter.Add(property.Name.ToString(), property.GetValue(objects, null).ToString());
            }
        }
    }
    return parameter;
    }

就我而言,当我将我的模型类传递给此方法时,它是正确的,但是在我的模型类中,我使用另一个这样的模型

public class Brand
{
    public MetaTags MetaTag { get; set; } // <---- Problem is here
    public string BrandName { get; set; }
}
public class MetaTags
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Language { get; set; }
}

它不是将 MetaTags 类属性添加到集合,而只是将 MetaTag 添加到集合中

我希望此方法返回此输出

key:Title       Value:value
key:Description Value:value
key:Language    Value:value
key:BrandName   Value:value

但是此方法返回此

key:MetaTag     Value:
key:BrandName   Value:value

我该怎么做?非常感谢您的帮助

从视图模型获取属性

在添加空字符串之前,请检查当前属性是否MetaTags。如果是这样,请递归使用此函数。

private NameValueCollection ObjectToCollection(object objects)
{
NameValueCollection parameter = new NameValueCollection();

Type type = objects.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance |
                                                BindingFlags.DeclaredOnly |
                                                BindingFlags.Public);
foreach (PropertyInfo property in properties)
{
    if (property.PropertyType == typeof(MetaTags))
    {
            parameter.Add(property.Name.ToString(),ObjectToCollection(property.GetValue(objects, null)))
    }
    else{
    if (property.GetValue(objects, null) == null)
    {
        parameter.Add(property.Name.ToString(), "");
    }
    else
    {
        if (property.GetValue(objects, null).ToString() != "removeProp")
        {
            parameter.Add(property.Name.ToString(), property.GetValue(objects, null).ToString());
        }
    }
    }
}
return parameter;
}