开发者

Can an ASP.Net control be configued to accept ANY attributes, even ones not defined as properties in the class definition?

开发者 https://www.devze.com 2022-12-09 14:26 出处:网络
Is it possible to define a control to have non-specified set of attributes?For instance: <MyPrefi开发者_高级运维x:MyControl SomeAttribute=\"SomeValue\" runat=\"server\"/>

Is it possible to define a control to have non-specified set of attributes? For instance:

<MyPrefi开发者_高级运维x:MyControl SomeAttribute="SomeValue" runat="server"/>

I don't want to define a property on the control class beforehand for "SomeAttribute." I'd really just like a HashTable or some other construct like this:

"SomeAttribute" => "SomeValue"

So this control can be used in many places with attributes that are essentially made up at runtime.

I'm wonder if there's some parsing method I can override which iterates through the attributes at parse time. I can:

  1. Look for a property with the name and set it
  2. If I don't find such a property, put the attribute name and value into a HashTable

Possible?


You want to use the IAttributeAccessor interface.

Defines methods used by ASP.NET server controls to provide programmatic access to any attribute declared in the opening tag of a server control.

Example control:

using System;
using System.Collections.Generic;
using System.Web.UI;

namespace App_Code.Controls {
    public class OutputAttributesControl : Control, IAttributeAccessor {
        private readonly IDictionary<String, String> _attributes = new Dictionary<String, String>();

        protected override void Render(HtmlTextWriter writer) {
            writer.Write("Attributes:<br/>");
            if (_attributes.Count > 0) {
                foreach (var pair in _attributes) {
                    writer.Write("{0} = {1} <br/>", pair.Key, pair.Value);
                }
            } else {
                writer.Write("(None)");
            }
        }

        public String GetAttribute(String key) {
            return _attributes[key];
        }

        public void SetAttribute(String key, String value) {
            _attributes[key] = value;
        }
    }
}

Invocation:

<AppCode:OutputAttributesControl runat="server" attr="value" />

Output:

Attributes:
attr = value

Caveats:

It seems that SetAttribute is only called on attributes that can not be resolved normally. This means you'll not see the id- or the runat-attribute in your code. Assigned properties (attr="<%= DateTime.Now %>") show up as an empty string. Databound properties does not show up at all in design mode, but works in normal mode (assuming that someone called DataBind, as usual).

0

精彩评论

暂无评论...
验证码 换一张
取 消