描述:在HTML文件中用某个符号字符串去表示一个标签,在ashx代码中即可用变量名去代替这个标签名
html文件:
<table border="1" cellpadding="0" cellspacing="0"> <tr> <td style="color:Red">姓名</td> <td onclick="alert('@name你好');">@name</td> </tr> <tr> <td>年龄</td> <td>@age</td> </tr> </table>
ashx文件:
context.Response.ContentType = "text/html"; string name = "张三"; int age = 20; string FileName = context.Server.MapPath("~/HTMLPage1.htm"); string Html1 = File.ReadAllText(FileName); string newHtml = Html1.Replace("@name",name).Replace("@age",age.ToString()); context.Response.Write(newHtml);
案例:显示数据库内容到网页上
html文件:
<table border="1" cellpadding="0" cellspacing="0"> <thead> <tr> @miHead </tr> </thead> @miFlow </table>
ashx文件:
context.Response.ContentType = "text/html"; string[] miHead = {"NO","生产流程","构成","条件","模治具编号","定位孔","方向", "?/P","P/S","步距","制作指示","变更","改"}; StringBuilder sb1 = new StringBuilder(); for (int i = 0; i < miHead.Length; i++) { sb1.Append("<th>" + miHead[i] + "</th>"); } StringBuilder sb2 = new StringBuilder(); DataTable table = SQLHelper.ExecuteReader("select * from Main_Flow"); int j = 1; foreach (DataRow row in table.Rows) { sb2.Append("<tr><td>" + j + "</td><td>" + row["name"] + "</td>"); for (int i = 0; i < miHead.Length - 2; i++) { sb2.Append("<td></td>"); } sb2.Append("</tr>"); j++; } string fileName = context.Server.MapPath("~/modelInput.htm"); string html = File.ReadAllText(fileName); html = html.Replace("@miHead", sb1.ToString()).Replace("@miFlow", sb2.ToString()); context.Response.Write(html);