溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ASP.NET中如何動態(tài)生成靜態(tài)頁面

發(fā)布時間:2021-07-16 14:23:55 來源:億速云 閱讀:117 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹ASP.NET中怎么動態(tài)生成靜態(tài)頁面,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

首先制作一個模板頁,暫時命名為template.htm,示例代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <div>
        $content$
    </div>
</body>
</html>
然后制作制作一個動態(tài)頁面,在這里我們通過一個按鈕點擊事件來生成靜態(tài)頁面。
前臺頁面主要代碼(Default.aspx):

復制代碼 代碼如下:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
        <asp:TextBox ID="txtContent" runat="server" Height="179px" TextMode="MultiLine" Width="350px"></asp:TextBox><br /> 
        <br /> 
        <asp:Button ID="btnMake" runat="server" OnClick="btnMake_Click" Text="生成靜態(tài)頁" /> 
    </div> 
    </form> 
</body> 
</html> 


后臺頁面主要代碼(Default.aspx.cs):

復制代碼 代碼如下:


protected void btnMake_Click(object sender, EventArgs e) 
    { 
        //替換掉模板中的特征字符    
        string mbPath = Server.MapPath("template.htm"); 
        Encoding code = Encoding.GetEncoding("UTF-8"); 
        StreamReader sr = null; 
        StreamWriter sw = null; 
        string str = null; 
        //讀取    
        try 
        { 
            sr = new StreamReader(mbPath, code); 
            str = sr.ReadToEnd(); 
        } 
        catch (Exception ex) 
        { 
            throw ex; 
        } 
        finally 
        { 
            sr.Close(); 
        } 
        //根據(jù)時間自動重命名,擴展名也可以自行修改    
        string fileName = DateTime.Now.ToString("yyyyMMddHHmm") + ".htm"; 
        str = str.Replace("$content$", txtContent.Text);//替換content   
        //生成靜態(tài)文件    
        try 
        { 
            sw = new StreamWriter(Server.MapPath("~/") + fileName, false, code); 
            sw.Write(str); 
            sw.Flush(); 
        } 
        catch (Exception ex) 
        { 
            throw ex; 
        } 
        finally 
        { 
            sw.Close(); 
            Response.Write("<a href=" + fileName + " mce_href=" + fileName + " target=_blank>" + fileName + "</a>已經(jīng)生成!"); 
        } 
    } 

關(guān)于ASP.NET中怎么動態(tài)生成靜態(tài)頁面就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI