Recently, I suddenly wanted to make the news management module of the project a static page. I found a lot of good articles on the Internet and recorded them here. Now, the generation of static pages does not implement the paging function. The main principle is to read the database data and replace the content on the static template page.
First, create a template page named template.htm. The sample code is as follows:
<! 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>
Create a dynamic page, and click an event to generate a static page.
Main Code of the front-end page (Default. aspx ):
Copy codeThe Code is as follows:
<% @ 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 = "generate static page"/>
</Div>
</Form>
</Body>
</Html>
Main Code of the background page (Default. aspx. cs ):
Copy codeThe Code is as follows:
Protected void btnMake_Click (object sender, EventArgs e)
{
// Replace the feature characters in the template
String mbPath = Server. MapPath ("template.htm ");
Encoding code = Encoding. GetEncoding ("UTF-8 ");
StreamReader sr = null;
StreamWriter sw = null;
String str = null;
// Read
Try
{
Sr = new StreamReader (mbPath, code );
Str = sr. ReadToEnd ();
}
Catch (Exception ex)
{
Throw ex;
}
Finally
{
Sr. Close ();
}
// Automatically rename the file according to the time, and the extension can be modified by yourself
String fileName = DateTime. Now. ToString ("yyyyMMddHHmm") + ". htm ";
Str = str. Replace ("$ content $", txtContent. Text); // Replace content
// Generate static files
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> generated! ");
}
}
When there is a large volume of news, this will inevitably increase the Storage pressure on the server. We will temporarily record it and wait for the graduation project to consider adding the dynamic generation of static pages and the static page paging function.