.NET 利用靜態頁模板網頁生成小計

知識小計:將數據庫文件讀取出,嵌套到固定靜態頁模板中,生成對應網頁。簡陋版

1.假如你已經拿到了數據庫裏所需要生成靜態頁的數據--List,,並進行遍歷

2.設置靜態頁模板中數據對應位置,佔位符,,$name最好和數據庫字段一致,便於區分,

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>$name
        </div>
    </form>
</body>
</html>

3.敲代碼--思路是,先拿到靜態頁模板地址,獲取靜態頁內容,替換靜態頁內容,設置靜態頁保存路徑,保存靜態頁

  • 拿到靜態頁模板:string filePath=HttpContext.Current.Request.MapPath("/template.html");
  • 獲取靜態頁內容:string fileContent=File.ReadAllText(filePath);
  • 替換  fileContent=fileContent.Replace("$name",ListItem.name);//如果多個就重複replace(“$d”,name).replace()....
  • 創建文件保存路徑 string dir="/文件夾1"+"/文件夾2";//根據需要設置合適路徑  最後一個字符串不加"/"就是生成網頁的名字前綴
  • 判斷路徑中有沒有文件,沒有就創建: Directory.CreatDirectory(Path.GetDirectoryName(HttpContext.Requext.MapPath(dir)));
  • 生成網頁文件名稱:string dirName=dir+item.ID+".html";
  • 保存文件(保存文件的地址,文件內容,文件格式)  File.WriteAllText(HttpContext.Current.request.MapPath(dirName),fileContent,System.Text.Encoding.UTF8);
  • 完成  嘿嘿純手敲,爽滴很

4.源代碼:

foreach (var item in list)
            {
                string filePath = HttpContext.Current.Request.MapPath("/moban/detail.html");
                string fileContext = File.ReadAllText(filePath);
                fileContext = fileContext.Replace("$name", item.name);
                string dir = "htmldetail/" + +item.ID+ "/";//根據日期創建文件夾
                Directory.CreateDirectory(Path.GetDirectoryName(HttpContext.Current.Request.MapPath(dir)));
                string fullDir = dir + item.ID + ".html";
                File.WriteAllText(HttpContext.Current.Request.MapPath(fullDir), fileContext, System.Text.Encoding.UTF8);

            }

5.可能會出現的問題:生成的靜態頁亂碼!!

打開你的html模板,設置編碼格式爲UTF-8,重新生成靜態頁,如果還不行,就將html以txt方式打開,然後另存爲對應編碼格式的html,然後在生成靜態頁,問題解決!

 6.結果:

動腦也要多動手,多動手 多動手。 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章