在進(jìn)行 ASP.NET 開發(fā)時(shí),有時(shí)候需要對(duì)頁(yè)面輸出的最終 HTML 源代碼進(jìn)行控制,是頁(yè)面的 render 方法中很容易實(shí)現(xiàn)這個(gè)功能。下面就是一個(gè)實(shí)現(xiàn)的方法,注釋都在代碼中。
ASPX 代碼
<%@ 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
{
// 將當(dāng)前頁(yè)面的內(nèi)容呈現(xiàn)到臨時(shí)的 HtmlTextWriter 對(duì)象中
base.Render(htmlWriter);
htmlWriter.Close();
// 得到當(dāng)前頁(yè)面的全部?jī)?nèi)容
content = stringWriter.ToString();
// 替換頁(yè)面中的部分內(nèi)容
string newContent = content.Replace("[mxh]", "孟憲會(huì)");
// 將新頁(yè)面的內(nèi)容顯示出來(lái)
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>孟憲會(huì)之替換頁(yè)面呈現(xiàn)內(nèi)容測(cè)試</title>
</head>
<body>
<form id="form1" runat="server">
[mxh]
</form>
</body>
</html>