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

ASP.NET 動態生成靜態 HTML 頁面並實現內容分頁完整實作

     編輯:ASP.NET 基礎

架構概覽

採用「模板替換 + 伺服器端生成」模式:前端編輯內容 → 後端讀取模板 → 替換標記 → 切割長文 → 生成多個 .shtml 靜態檔案 → 存入資料庫記錄路徑。

1. 靜態模板頁面 (template.html)

預留標記:Title、NewsId、Time、Content、Pager,供後端程式替換。

<div align="center">Title</div>
<div>瀏覽 <font color="red"><script src="/ClickCount.aspx?NewsId=NewsId"></script></font> 次 Time</div>
<div>Content</div>
<div>Pager</div> <!-- 分頁導航將注入此處 -->

2. 後台新增新聞介面 (NewsAdd.aspx)

使用 FCKeditor 富文本編輯器,表單包含標題與內容兩欄位。

3. 核心生成邏輯 (NewsAdd.aspx.cs)

關鍵步驟解析

  1. 內容切割:以 | 字元分割長文,每段生成一個分頁。
  2. 目錄管理:依日期建立資料夾(如 NewsFiles/240115/),避免單一目錄檔案過多。
  3. 模板讀取與替換:使用 StreamReader 讀取模板,StringBuilder 累加替換後內容。
  4. 分頁導航生成:動態構建「上一頁、頁碼、下一頁」HTML 表格,處理首尾頁邊界條件。
  5. 檔案寫入:透過 FileStream + StreamWriter 輸出 .shtml 檔案。

核心代碼片段

protected void Button1_Click(object sender, EventArgs e)
{
    string strDate = DateTime.Now.ToString("yyMMddHHmmss");
    string strFileName = strDate + ".shtml";
    string strTitle = Request.Form["Title"].Trim();
    string strContent = Request.Form["Content"].Trim();
    string[] contents = strContent.Split('|');
    int pageCount = contents.Length;

    // 存入資料庫略...

    string dir = Server.MapPath($"~/NewsFiles/{DateTime.Now:yyMMdd}");
    if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

    for (int i = 0; i < pageCount; i++)
    {
        StringBuilder html = new StringBuilder();
        // 讀取模板
        using (StreamReader sr = new StreamReader(Server.MapPath("~/NewsFiles/template.html"), Encoding.GetEncoding("gb2312")))
        {
            string line;
            while ((line = sr.ReadLine()) != null) html.Append(line);
        }

        // 替換通用標記
        html.Replace("Title", strTitle);
        html.Replace("NewsId", newId.ToString());
        html.Replace("Time", DateTime.Now.ToString("yyyy/MM/dd"));
        html.Replace("Content", contents[i]);

        // 生成分頁導航 HTML (strTable)
        // ... 邏輯處理 upUrl, Number, downUrl 替換 ...

        html.Replace("Pager", strTable);

        // 寫入檔案
        string filePath = (i == 0) 
            ? Path.Combine(dir, strDate + ".shtml")
            : Path.Combine(dir, $"{strDate}_{i}.shtml");
        
        using (FileStream fs = new FileStream(filePath, FileMode.Create))
        using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
        {
            sw.Write(html.ToString());
        }
    }
}

優化建議

  • 改用 Razor 模板引擎或 System.Text.Json 序列化模型,提升可維護性。
  • 引入非同步 I/O (async/await) 避免阻塞請求執行緒。
  • 加入錯誤重試與交易機制,確保資料庫記錄與檔案生成一致性。
  • 考慮雲端儲存 (Blob Storage) 取代本機檔案系統,利於水平擴展。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved