Control类的Render方法在WebControl类中被被分成三部分
1:RenderBeginTag,呈现标签的开始
2:RenderContents,呈现标签的内容
3:RenderEndTag,呈现标签的结束
一般情况下不重写RenderBeginTag和RenderEndTag
RenderBeginTag生成什么样的标签
由WebControl.TagKey和WebControl.TagName决定
默认的TagKey是Span
(假设你想直接输出文本,那么你重写的TagKey是Unknown,TagName是string)
WebControl提供一个AddAttributeToRender方法
此方法在RenderBeginTag之前执行
我们可以重写这个方法来初始化标签的样式
(注意重写此方法一定要初始化基类base.AddAttributeToRender(yourHtmlTextWriter))
看代码
using
System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace hellowControl
{
public class HellowControl:WebControl
{
// 重写TagKey属性,让他生成div的标签
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
// 重写AddAttributesToRender方法,此方法在RenderBeginTag之前发生
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base .AddAttributesToRender(writer);
writer.AddStyleAttribute(HtmlTextWriterStyle.TextAlign, " center " );
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Src, " noimage_s.jpg " );
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
}
}
}
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace hellowControl
{
public class HellowControl:WebControl
{
// 重写TagKey属性,让他生成div的标签
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
// 重写AddAttributesToRender方法,此方法在RenderBeginTag之前发生
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base .AddAttributesToRender(writer);
writer.AddStyleAttribute(HtmlTextWriterStyle.TextAlign, " center " );
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Src, " noimage_s.jpg " );
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
}
}
}