I think I may be approaching this issue wrong but here goes... I'm trying to apply attributes (non-html) to web controls through the designer such as:
开发者_如何学C [MHCSecurityAttribute("testpermission", true)]
protected global::System.Web.UI.WebControls.TextBox test1;
The idea is to loop through the controls collection within a base page and pull back these attributes and then "lock down" the control by either making readonly or enabled/disabled...
Here is the issue though... The control collection is the instance im after but Control.GetType is going to get the type associated with say a TextBox... while I'm really looking for the attribute I set on the page itself for that instance. On the page itself I'm not how to even reference the type. On the page if I look on the this.GetType().GetMembers()... I still don't see my attribute for my control. Any thoughts?
well heres the answer....
First you need to look at the page correctly by calling this.GetType().BaseType. Turns out that the this operator you use in aspx pages ends up being a derived type...
Once that is done you can find the attributes on fields
const BindingFlags bf = BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
foreach (Control c in controls) { bool useMHCSecurity = c is IMHCSecurityControl; if (c.ID != null) { FieldInfo info = parentPage.GetField(c.ID, bf); if (info != null) { object[] attributes = info.GetCustomAttributes(typeof(MHCSecurityAttribute), false);
note you have to check that 1) you have an ID attrib (you get literal controls and such which wouldn't have attributes assigned) 2) make sure you get and FieldInfo var back 3) make sure you have moved the control definitions from the designer file to the code behind file (the designer will overwrite)
精彩评论