项目要求
练习2:
@RPHelper.Include("~/1.html")
把~/1.html内容原样输出到这个位置
是项目 ProjectLX001
第一步:假定读取的html文件是这个
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<input type="text" id="article" name="article" />
<br /><br />
<input type="checkbox" id="hobby" name="hobby" />
<br /><br />
<select id="xingqu" name="xingqu">
<option value="1">C语言</option>
<option value="2">Java语言</option>
<option value="3">C#语言</option>
<option value="4">php语言</option>
</select>
<input type="button" value="提交" />
</body>
</html>
第二步:写类HtmlHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RazorEngine;
using System.IO;
using RazorEngine.Text;
namespace ProjectLX001
{
public class HtmlHelper
{
//1.封装一个ParseRazor方法,避免每次都为动态程序集生成别名
public static string ParseRazor(HttpContext context, string csHtmlVirtualPath, object model)
{
//1.1 拿到模板文件的 的虚拟路径
string fullPath = context.Server.MapPath(csHtmlVirtualPath);
//1.2 读取模板文件csHtml
string cshtml = File.ReadAllText(fullPath);
//1.3 给模板文件生成的动态程序集起一个别名字,防止,重复编译生成动态程序集,影响网站的速度性能
//这里用时间
string cacheName = fullPath + File.GetLastWriteTime(fullPath);
//1.4 用model替换模板中变量值的内容
string html = Razor.Parse(cshtml, model, cacheName);
return html;
}
//2.封装一个OutHtml方法,将1.html文件读取
public static RawString Include(HttpContext context, string vitualHtmlPath)
{
//2.1 取得html的虚拟路径
string fullHtmlPath = context.Server.MapPath(vitualHtmlPath);
//2.2 IO读取html文件中的内容
string html = File.ReadAllText(fullHtmlPath);
//2.3 返回
return new RawString(html);
}
}
}
第三步:写模板文件1.cshtml
<!--添加HtmlHelper的命名空间-->
@using ProjectLX001
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
@HtmlHelper.Include();
</body>
</html>
第四步:读取模板文件一般处理程序
using RazorEngine.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProjectLX001
{
/// <summary>
/// _1 的摘要说明
/// </summary>
public class _1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";//1.修改为html
//2.读取cshtml模板
string html = HtmlHelper.ParseRazor(context,"~/1.html",null);
//3.返回浏览器端
context.Response.Write(html);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
运行结果