知识小计:将数据库文件读取出,嵌套到固定静态页模板中,生成对应网页。简陋版
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.结果:
动脑也要多动手,多动手 多动手。