您的位置:首页 > 编程语言 > ASP

ASP.NET动态生成静态页面的实例代码

2013-07-27 22:19 609 查看
实现静态页面的生成并没有实现分页功能。其主要原理就是读取数据库的数据然后替换掉静态模板页的内容。

1,首先制作一个模板页,暂时命名为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>生成静态页面_www.jbxue.com</title>
</head>
<body>
<div>
$content$
</div>
</body>
</html>


然后制作制作一个动态页面,在这里我们通过一个按钮点击事件来生成静态页面。

2,前台页面代码(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>前台页面代码_www.jbxue.com</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="生成静态页" />
</div>
</form>
</body>
</html>


3,后台页面主要代码(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();
}
//根据时间自动重命名,扩展名也可以自行修改
string fileName = DateTime.Now.ToString("yyyyMMddHHmm") + ".htm";
str = str.Replace("$content$", txtContent.Text);//替换content
//生成静态文件
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>已经生成!");
}
}


当新闻量很大时会增加服务器的存储压力,暂时记录下来等毕业设计时再考虑增加动态生成静态页面,静态页面分页的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: