我已经创建了一个自定义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; }
}
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>我的问题:
BodyStyle以HTML BodyStyle的形式出现,为什么WrapperTag没有出现?发布于 2011-08-31 21:34:09
BodyStyle是写出来的,因为它存在于ViewState中。在OnRender期间,HtmlGenericControl将所有ViewState项作为属性添加。WrapperTag不在ViewState中,因此不会作为属性编写。_bag是StateBag。
下面是来自反射器的呈现属性实现:
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;
}
}https://stackoverflow.com/questions/7263559
复制相似问题