Search code examples
asp.netexpandoexpandoobjectdynamicobject

System.Dynamic ExpandoControl is it possible?


I'm trying to figure out how to create a web server control which is basically an ExpandoObject.

The desire is to automatically create a property on the control when it is created in the aspx markup.

For example:

<x:ExpandoControl someProperty="a value"></x:ExpandoControl>

Where the someProperty attribute does not yet exist as a property on the control.

I should also mention that I don't strictly need any functionality of Control or WebControl. I just need to be able to declare it in markup with runat="server" (which in and of itself may require it to be a control, at least that's what I'm thinking).

Is it possible? If so how can I get started?

Many thanks.


Solution

  • I think your first bet would be to implement IAttributeAccessor:

    public interface IAttributeAccessor
    {
        string GetAttribute(string key);
        void SetAttribute(string key, string value);
    }
    

    The ASP.NET page parser calls IAttributeAccessor.SetAttribute for each attribute it cannot map to a public property.

    So perhaps you can start with

    public class ExpandoControl : Control, IAttributeAccessor
    {
        IDictionary<string, object> _expando = new ExpandoObject();
    
        public dynamic Expando
        {
            {
                return _expando;
            }
        }
    
        void IAttributeAccessor.SetValue(string key, string value)
        {
            _expando[key] = value;
        }
    
        string IAttributeAccessor.GetValue(string key)
        {
            object value;
            if (_expando.TryGetValue(key, out value) && value != null)
                return value.ToString();
            else
                return null;
        }
    }