如何从C#背后的代码获取用户控件的更改的类名

时间:2019-01-30 09:12:27

标签: c# jquery asp.net class reflection

我创建了自己的具有属性CssClass的用户控件,该属性与用户控件内的TextBox之一相连,并且具有一些默认类。

使用此控件构建页面后,将另一个类(使用jQuery)添加到我的用户控件中。

我想要实现的是在代码中获取所有类名。目前,我只得到了默认的类名,而没有一个额外的类名。我对标准Web控件没有这个问题。

如果有人知道如何实现?

编辑:

需要明确说明我要实现的目标:我的UserControlTextBoxclass = "defaultClass"。我打开了呈现控件的网站,并且看到我的TextBox有一个class = "defaultClass"。然后,我单击了某个按钮,该按钮使用JQuery向我的TextBox添加了另一个类,因此之后我的TextBox有2个classes = "defaultClass newClass"。最后,单击“结束按钮”,从页面上收集了所有控件,并检查每个控件是否包含类newClass。上面的情况适用于任何Web控件,但是对于我的UserControl,我只能看到"defaultClass"

代码:

foreach (Control ctrl in all)
{
    // Some code
    UserControl usc = ctrl as UserControl;
    if (usc != null) {
        var classes = usc.GetType().GetProperty("[PROPERTYNAME]").GetValue(usc,null).ToString();
        //HERE I GOT ONLY DEFAULT CLASS NAME WITHOUT ADDITIONAL ONE I ADDED BY JQUERY
    }
}


* "all" is a ControlCollection of page.Controls

1 个答案:

答案 0 :(得分:0)

我对您想要的东西有点困惑...

如果要获取类名本身,则为

usc.GetType().name

但是,如果要获取UserControl类中所有属性的列表,则必须要求整个列表。您目前只要求一种特定的财产。因此,尝试:

var classes = usc.GetType().GetProperties();

如果只需要类名,请使用相应属性的PropertyType属性。

另一个错误来源可能是:您的jquery是否为属性生成 getter和setter ?如果不是,则这些属性对“属性”不可见,而是作为“ 字段”,而是使用GetFields()。

这是一个检索属性的示例代码:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Reflection_Test
{
    class UserControl
    {
        public int test { get; set; } // if no getter/setter is set, this is considered as field, not property
        public bool falsetrue { get; set; } // if no getter/setter is set, this is considered as field, not property
        public UserControl control { get; set; } // if no getter/setter is set, this is considered as field, not property

        public UserControl()
        {
            test = 23;
            falsetrue = true;
            control = this;
        }

        public List<string> GetAttributes()
        {
            PropertyInfo[] temp = this.GetType().GetProperties();
                //this.GetType().GetProperties();
            List<string> result = new List<string>();

            foreach(PropertyInfo prop in temp)
            {
                result.Add(prop.PropertyType.ToString());
            }

            return result;
        } 

    }
}