C# 防止ASP.NET属性在自定义控件中显示为属性
我创建了一个自定义ASP.NET控件,该控件将充当带有特定包装标签的容器:C# 防止ASP.NET属性在自定义控件中显示为属性,c#,.net,asp.net,html,C#,.net,Asp.net,Html,我创建了一个自定义ASP.NET控件,该控件将充当带有特定包装标签的容器: class Section : System.Web.UI.HtmlControls.HtmlGenericControl { public string WrapperTag // Simple interface to base-class TagName { get { return base.TagName; } set { base.TagName = value
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);
}
}
这是毫无疑问的,除了由于某种原因,BodyStyle
属性也作为属性出现在HTML输出中。因此,如果我使用控件:
<xx:Section runat="server" WrapperTag="div" BodyStyle="background-color:#ffeeaa;"><other stuff /></xx:Section>
这将产生:
<div BodyStyle="background-color:#ffeeaa;" style="background-color:#ffeeaa;"><other stuff HTML output /></div>
我正在尝试生成输出:
<div style="background-color:#ffeeaa;"><other stuff HTML output /></div>
我的问题是:
- 为什么
显示为HTML属性BodyStyle
- 既然出现了
,为什么BodyStyle
也不出现WrapperTag
BodyStyle
被写出,因为它存在于视图状态中。在OnRender
期间,HtmlGenericControl
将所有ViewState
项添加为属性WrapperTag
不在ViewState
中,因此不作为属性写入<代码>\u bag
是状态袋
以下是来自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);
}
}
}
}
}
将代码更改为:
private string bodyStyle;
public string BodyStyle
{
get
{
return bodyStyle ?? string.Empty;
}
set
{
bodyStyle = value;
}
}
BodyStyle
被写出,因为它存在于ViewState
中。在OnRender
期间,HtmlGenericControl
将所有ViewState
项添加为属性WrapperTag
不在ViewState
中,因此不作为属性写入<代码>\u bag是状态袋
以下是来自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);
}
}
}
}
}
将代码更改为:
private string bodyStyle;
public string BodyStyle
{
get
{
return bodyStyle ?? string.Empty;
}
set
{
bodyStyle = value;
}
}