palswim
palswim

Reputation: 12140

Prevent ASP.NET Properties from Showing as Attributes in Custom Controls

I have created a Custom ASP.NET Control which will act as a container with a specific wrapping tag:

class Section : System.Web.UI.HtmlControls.HtmlGenericControl
{
    public string WrapperTag // Simple interface to base-class TagName
    {
        get { return base.TagName; }
        set { base.TagName = value; }
    }


    public string BodyStyle
    {
        get
        {
            object o = ViewState["BodyStyle"];
            return (o == null) ? "" : (string)o;
        }
        set
        {
            ViewState["BodyStyle"] = value;
        }
    }

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        Attributes["style"] = BodyStyle + ";";
        base.Render(writer);
    }
}

This works without issue, except that the BodyStyle property also appears as an attribute in the HTML output for some reason. So, if I use the control:

<xx:Section runat="server" WrapperTag="div" BodyStyle="background-color:#ffeeaa;"><other stuff /></xx:Section>

This outputs:

<div BodyStyle="background-color:#ffeeaa;" style="background-color:#ffeeaa;"><other stuff HTML output /></div>

I'm trying to produce the output:

<div style="background-color:#ffeeaa;"><other stuff HTML output /></div>

My questions:

Upvotes: 1

Views: 261

Answers (1)

TheCodeKing
TheCodeKing

Reputation: 19240

BodyStyle is written out because it exists in the ViewState. During OnRender the HtmlGenericControl adds all ViewState items as attributes. WrapperTag isn't in the ViewState so doesn't get written as an attribute. _bag is the StateBag.

Here's the render attributes implementation from reflector:

public void Render(HtmlTextWriter writer)
{
    if (this._bag.Count > 0)
    {
        IDictionaryEnumerator enumerator = this._bag.GetEnumerator();
        while (enumerator.MoveNext())
        {
            StateItem stateItem = enumerator.Value as StateItem;
            if (stateItem != null)
            {
                string text = stateItem.Value as string;
                string text2 = enumerator.Key as string;
                if (text2 != null && text != null)
                {
                    writer.WriteAttribute(text2, text, true);
                }
            }
        }
    }
}

Change your code to this:

private string bodyStyle;

public string BodyStyle
{
    get
    {
        return bodyStyle ?? string.Empty;
    }
    set
    {
        bodyStyle = value;
    }
}

Upvotes: 1

Related Questions