HtmlTextWriter

HtmlTextWriter的构造函数要求必须传递一个与TextWriter接口兼容的实例。大家可以根据需要选择合适的TextWriter接口实 现类,因为该类的选择将决定最终生成的Html文本的输出方式,例如我想把结果输出到一个TextBox中,于是我就使用了StringWriter类的 实例作为参数传入:
   StringWriter sw=new System.IO.StringWriter();
   HtmlTextWriter writer=new HtmlTextWriter(sw);

如果要获得结果,只需要使用sw.toString()就可以了。注意,HtmlTextWriter本身不提供输出方法或属性。

ContractedBlock.gif ExpandedBlockStart.gif Code
protected override void Render(HtmlTextWriter writer) 
{     
    
// Set attributes and values along with attributes and styles  
    
// attribute defined for a <span> element.
    writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "alert('Hello');");
    writer.AddAttribute(
"CustomAttribute""CustomAttributeValue");
    writer.AddStyleAttribute(HtmlTextWriterStyle.Color, 
"Red");
    writer.AddStyleAttribute(
"Customstyle""CustomStyleValue");
    writer.RenderBeginTag(HtmlTextWriterTag.Span);
    
// Create a space and indent the markup inside the 
    
// <span> element.
    writer.WriteLine();
    writer.Indent
++;
    writer.Write(
"Hello");
    writer.WriteLine();
    
    
// Controls the encoding of markup attributes
    
// for an <img> element. Simple known values 
    
// do not need encoding.
    writer.AddAttribute(HtmlTextWriterAttribute.Alt, 
        
"Encoding, \"Required\""
        
true);
    writer.AddAttribute(
"myattribute"
        
"No &quot;encoding &quot; required"
        
false);
    writer.RenderBeginTag(HtmlTextWriterTag.Img);
    writer.RenderEndTag();
    writer.WriteLine();

    
// Create a non-standard markup element.
    writer.RenderBeginTag("MyTag");
    writer.Write(
"Contents of MyTag");
    writer.RenderEndTag();
    writer.WriteLine();

    
// Create a manually rendered <img> element
    
// that contains an alt attribute.
    writer.WriteBeginTag("img");
    writer.WriteAttribute(
"alt""A custom image.");
    writer.Write(HtmlTextWriter.TagRightChar);
    writer.WriteEndTag(
"img");
    writer.WriteLine();

    writer.Indent
--;
    writer.RenderEndTag();

}

 

转载于:https://www.cnblogs.com/tangjian/archive/2009/03/28/1424062.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值