【问题标题】:How to get changed class name of User Control from code behind C#如何从 C# 后面的代码中获取更改的用户控件的类名
【发布时间】:2019-01-30 09:12:26
【问题描述】:

我创建了自己的用户控件,其属性 CssClass 与我的用户控件中的一个 TextBox 连接,并且默认具有一些类。

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

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

如果有人知道如何实现这一目标?

编辑:

我想要实现的小澄清:我有我的UserControlTextBox,它有class = "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

【问题讨论】:

  • 您应该告诉我们all 是什么以及您是如何获得它的。
  • 添加在问题的底部。这是page.controls 中的ControlCollection
  • 缺少信息。您的控件是否在 Page_Load 中初始化? Page_PreRender?另外,您在哪里使用此代码?因此,您可能会失去班级价值。
  • 在 PreRender 上,当我想从网站获取信息时,我将此代码用作 Button 的一部分。但如果我失去了它,为什么我仍然得到默认的?
  • 失去我的意思是您的控件被您的设置覆盖,该设置将应用于控件创建。

标签: c# jquery asp.net class reflection


【解决方案1】:

我对你想要什么有点困惑......

如果要获取类名本身,就是

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

    }
}

【讨论】:

  • 我对我的问题进行了澄清
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 2016-05-02
  • 2017-03-29
  • 2013-07-02
  • 2012-03-09
相关资源
最近更新 更多