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

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

 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();

}

 

相关文章:

  • 2021-12-31
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
  • 2021-10-28
猜你喜欢
  • 2022-02-28
  • 2021-10-21
  • 2021-07-05
  • 2022-12-23
相关资源
相似解决方案