Reputation: 12140
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:
BodyStyle
appear as an HTML attribute?BodyStyle
appears, why doesn't WrapperTag
appear as well?Upvotes: 1
Views: 261
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