在进行 ASP.NET 开发时,有时候需要对页面输出的最终 HTML 源代码进行控制

在进行 ASP.NET 开发时,有时候需要对页面输出的最终 HTML 源代码进行控制,是页面的 render 方法中很容易实现这个功能。下面就是一个实现的方法,注释都在代码中。

 

[c-sharp] view plaincopy
 
  1. <%@ Page Language="C#" %>  
  2. <%@ Import Namespace="System.IO" %>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <script runat="server">  
  5.   protected override void Render(HtmlTextWriter writer)  
  6.   {  
  7.     string content = string.Empty;  
  8.     StringWriter stringWriter = new StringWriter();  
  9.     HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);  
  10.     try  
  11.     {  
  12.       // 将当前页面的内容呈现到临时的 HtmlTextWriter 对象中  
  13.       base.Render(htmlWriter);  
  14.       htmlWriter.Close();  
  15.       // 得到当前页面的全部内容  
  16.       content = stringWriter.ToString();  
  17.       // 替换页面中的部分内容  
  18.       string newContent = content.Replace("[mxh]""孟宪会");  
  19.       // 将新页面的内容显示出来  
  20.       writer.Write(newContent);  
  21.     }  
  22.     catch { }  
  23.     finally  
  24.     {  
  25.       stringWriter.Dispose();  
  26.       htmlWriter.Close();  
  27.       htmlWriter.Dispose();  
  28.     }  
  29.   }  
  30. </script>  
  31. <html xmlns="http://www.w3.org/1999/xhtml">  
  32. <head id="Head1" runat="server">  
  33.   <title>孟宪会之替换页面呈现内容测试</title>  
  34. </head>  
  35. <body>  
  36.   <form id="form1" runat="server">  
  37.   [mxh]  
  38.   </form>  
  39. </body>  
  40. </html>  

 

posted @ 2014-01-11 11:45  电工男  阅读(260)  评论(0编辑  收藏  举报