Recently suddenly want to put the project in the news management module to make static pages, found many good articles on the Internet, here to record, now just to achieve static page generation and did not implement paging function. The main principle is to read the database data and then replace the contents of the static template page.
First make a template page, temporarily 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 ">
<title></title>
<body>
<div>
$content $
</div>
</body>
Then make a dynamic page where we use a button click event to generate a static page.
Front page main code (Default.aspx):
Copy Code code 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 ">
<title></title>
<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>
Background page main code (Default.aspx.cs):
Copy Code code 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 renamed according to time, extension can also be modified by itself
String fileName = DateTime.Now.ToString ("yyyymmddhhmm") + ". htm";
str = str. Replace ("$content $", txtcontent.text);//replacement content
Generating 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> has been generated!" ");
}
}
When the news volume is very large, this will increase the storage pressure on the server, temporarily record the graduation design and then consider adding dynamic static page, static page paging function.