适用于消息宣布体系,比方sina、163等都是采纳动态生成html页面的。
适用于需动态定制页面的顺序。比方论坛、聊天室等。能够加载定制好的html页面,来增强雅观。
思绪
1. 应用如Dw-Mx如许的东西生成html花样的模板,在须要增加花样的处所到场特别标记(如$htmlformat$),动态生成文件时应用代码读取此模 板,然后取得前台输入的内容,增加到此模板的标记位置中,生成新文件名后写入磁盘,写入后再向数据库中写入相干数据。
2. 运用背景代码硬编码Html文件,能够运用HtmlTextWriter类来写html文件。
长处
1. 能够竖立异常复杂的页面,应用包含js文件的要领,在js文件内到场document.write()要领能够在所有页面内到场如页面头,广告等内容。
2. 静态html文件应用MS Windows2000的Index Server能够竖立全文搜刮引擎,应用asp.net能够以DataTable的体式格局获得搜刮效果。而Win2000的Index效劳没法查找xml文 件的内容。假如包含了数据库搜刮与Index索引两重查找,那末此搜刮功用将异常壮大。
3. 节约效劳器的负荷,要求一个静态的html文件比一个aspx文件效劳器资本节约很多。
瑕玷
思绪二: 假如用硬编码的体式格局,工作量异常大,须要异常多的html代码。调试难题。而且运用硬编码生成的html款式没法修正,假如网站替代款式,那末必须得从新编码,给后期带来庞大的工作量。
因而这里采纳的是第一种思绪
示列代码
1.定义(template.htm)html模板页面
<html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body > <table $htmlformat[0] height="100%" border="0" width="100%" cellpadding="10" cellspacing="0" bgcolor="#eeeeee" style="border:1px solid #000000"> <tr> <td width="100%" valign="middle" align="left"> <span style="color: $htmlformat[1];font-size: $htmlformat[2]">$htmlformat[3]</span> </td> </tr> </table> </body> </html>
2.asp.net代码:
//---------------------读html模板页面到stringbuilder对象里---- string[] format=new string[4];//定义和htmlyem标记数量一致的数组 StringBuilder htmltext=new StringBuilder(); try { using (StreamReader sr = new StreamReader("寄存模板页面的途径和页面名")) { String line; while ((line = sr.ReadLine()) != null) { htmltext.Append(line); } sr.Close(); } } catch { Response.Write("<Script>alert('读取文件毛病')</Script>"); } //---------------------给标记数组赋值------------ format[0]="background=/"bg.jpg/"";//背景图片 format[1]= "#990099";//字体色彩 format[2]="150px";//字体大小 format[3]= "<marquee>生成的模板html页面</marquee>";//文字说明 //----------替代htm里的标记为你想加的内容 for(int i=0;i<4;i++) { htmltext.Replace("$htmlformat["+i+"]",format[i]); } //----------生成htm文件------------------ try { using(StreamWriter sw=new StreamWriter("寄存途径和页面名",false,System.Text.Encoding.GetEncoding("GB2312"))) { sw.WriteLine(htmltext); sw.Flush(); sw.Close(); } } catch { Response.Write ("The file could not be wirte:"); }
小结
用此要领能够轻易的生成html文件。顺序运用了是轮回替代,因而对需替代大批元素的模板速率异常快。
更多Asp.net动态生成html页面的要领分享相干文章请关注ki4网!