在进行 ASP.NET 开发时,有时候需要对页面输出的最终 HTML 源代码进行控制,是页面的 render 方法中很容易实现这个功能。下面就是一个实现的方法,注释都在代码中。
view plaincopy to clipboardprint?
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected override void Render(HtmlTextWriter writer)
{
string content = string.Empty;
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
try
{
// 将当前页面的内容呈现到临时的 HtmlTextWriter 对象中
base.Render(htmlWriter);
htmlWriter.Close();
// 得到当前页面的全部内容
content = stringWriter.ToString();
// 替换页面中的部分内容
string newContent = content.Replace("[mxh]", "孟宪会");
// 将新页面的内容显示出来
writer.Write(newContent);
}
catch { }
finally
{
stringWriter.Dispose();
htmlWriter.Close();
htmlWriter.Dispose();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>孟宪会之替换页面呈现内容测试</title>
</head>
<body>
<form id="form1" runat="server">
[mxh]
</form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected override void Render(HtmlTextWriter writer)
{
string content = string.Empty;
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
try
{
// 将当前页面的内容呈现到临时的 HtmlTextWriter 对象中
base.Render(htmlWriter);
htmlWriter.Close();
// 得到当前页面的全部内容
content = stringWriter.ToString();
// 替换页面中的部分内容
string newContent = content.Replace("[mxh]", "孟宪会");
// 将新页面的内容显示出来
writer.Write(newContent);
}
catch { }
finally
{
stringWriter.Dispose();
htmlWriter.Close();
htmlWriter.Dispose();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>孟宪会之替换页面呈现内容测试</title>
</head>
<body>
<form id="form1" runat="server">
[mxh]
</form>
</body>
</html>
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/net_lover/archive/2010/02/25/5324455.aspx