首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 動態產生靜態 HTML 頁面:模板替換法完整實作

     編輯:關於ASP.NET

思路

  1. 利用如 Dw-Mx 等工具產生 HTML 格式模板,需添加格式處加入特殊標記(如 $htmlformat$),動態產生檔案時用程式碼讀取模板,再取得前台輸入內容添加到模板標記位置,產生新檔名後寫入磁碟,寫入後再向資料庫寫入相關資料。
  2. 使用後台程式碼硬編碼 HTML 檔案,可使用 HtmlTextWriter 類別寫 HTML 檔案。

優點

  1. 可建立非常複雜頁面,利用包含 JS 檔案方法,在 JS 檔案內加入 document.write() 可在所有頁面加入頁首、廣告等內容。
  2. 靜態 HTML 檔案利用 MS Windows 2000 Index Server 可建立全文搜尋引擎,利用 ASP.NET 以 DataTable 方式取得搜尋結果。Win2000 Index 服務無法查找 XML 檔案內容。若包含資料庫搜尋與 Index 索引雙重查找,搜尋功能將非常強大。
  3. 節省伺服器負載,請求靜態 HTML 檔案比 ASPX 檔案節省許多伺服器資源。

缺點

思路二:若用硬編碼方式,工作量極大,需非常多 HTML 程式碼。除錯困難。且硬編碼產生 HTML 樣式無法修改,若網站更換樣式,必須重新編碼,給後期帶來巨大工作量。

因此這裡採用第一種思路。

範例程式碼

1. 定義 (template.htm) HTML 模板頁面

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body >
<table $htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing="0" bgcolor="#eeeeee" style="border:1px solid #000000">
<tr>
<td width="100%" valign="middle" align="left">
<span style="color: $htmlformat[1];font-size: $htmlformat[2]">$htmlformat[3]</span>
</td>
</tr>
</table>
</body>
</html>

2. ASP.NET 程式碼:

//---------------------讀 HTML 模板頁面到 StringBuilder 物件裡----
string[] format=new string[4];//定義與 HTML 標記數目一致陣列
StringBuilder htmltext=new StringBuilder();
try
{
using (StreamReader sr = new StreamReader("存放模板頁面路徑與頁面名"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
htmltext.Append(line);
}
sr.Close();
}
}
catch
{
Response.Write("<Script>alert('讀取檔案錯誤')</Script>");
}
//---------------------給標記陣列賦值------------
format[0]="background=\"bg.jpg\"";//背景圖片
format[1]= "#990099";//字型顏色
format[2]="150px";//字型大小
format[3]= "<marquee>產生的模板html頁面</marquee>";//文字說明
//----------替換 HTML 裡標記為你想加內容
for(int i=0;i<4;i++)
{
htmltext.Replace("$htmlformat["+i+"]",format[i]);
}
//----------產生 HTML 檔案------------------――
try
{
using(StreamWriter sw=new StreamWriter("存放路徑與頁面名",false,System.Text.Encoding.GetEncoding("GB2312")))
{
sw.WriteLine(htmltext);
sw.Flush();
sw.Close();
}
}
catch
{
Response.Write ("The file could not be wirte:");
}

小結

用此方法可方便產生 HTML 檔案。程式使用迴圈替換,因此對需替換大量元素模板速度非常快。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved