0

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
ChrisS
  • 2,595
  • 3
  • 18
  • 19

1 Answers1

1

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;
    }
}
Ruben
  • 15,217
  • 2
  • 35
  • 45
  • Brilliant! I do remember reading about this interface quite some time ago but have forgotten about it. I think you're right. It just might work exactly the way I need it to. Thanks so much for your help. I'll update this as the accepted answer when I get a chance to try it out later tonight. – ChrisS Feb 26 '12 at 21:54
  • This does indeed work. The only limitation is the fact that the value must be string value but with some crafty serialization and de-serialization this will have to do for now. – ChrisS Feb 26 '12 at 22:27