RazorEngine引擎就是将cshtml模板文件进行了字符串的拼接,然后,再封装为一个程序集。。。再通过一般处理程序,进行调用。。
下面来封装一个方法。来简化上一节内容的操作;
1.获得虚拟路径; 2.从虚拟路径中读取cshtml模板中的内容; 3.给cshtml模板文件取一个别名字;(提高网站性能) 4. 用model替换模板中的变量;
步骤:项目名字—右键—-添加—–RPcshtmlHelper
using RazorEngine;
using RazorEngine.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace Web2
{
public class RPcshtmlHelper
{
//弄清关系,不要怀疑工具的错误,检查自己操作的问题
//1.封装一个方法,省去了每次都重复自己添加cacheName的麻烦
public static string ParseRazor(HttpContext context, string csHtmlVirtualPath, object model)
{
//2.拿到虚拟路径
string fullPath = context.Server.MapPath(csHtmlVirtualPath);
//3.读取模板
string cshtml = File.ReadAllText(fullPath);
//4.给模板文件取一个别名字
string cacheName = fullPath + File.GetLastWriteTime(fullPath);
//5.用model替换变量
string html = Razor.Parse(cshtml,model,cacheName);
//6.返回模板文件内容
return html;
}
//1.定义一个简单的《静态》方法,作为测试,这里的方法是在cshtml模板文件中调用的
public static HtmlEncodedString Test1()
{
return new HtmlEncodedString("<input type='text' />");
}
// 同样定义第二个《静态》方法
public static RawString Test2()
{
return new RawString("<input type='text' />");
}
}
}
<!--1.首先,在模板文件中读取RPcshtmlHelper的命名空间-->
@using Web2
<!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>
<!--2.调用类中的测试方法Test1--Test2-->
html标签转义过的 @RPcshtmlHelper.Test1()<br />
html标签没有转义过的 @RPcshtmlHelper.Test2()
<!--3.添加一个一般处理处理程序,调用该模板文件-->
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Web2
{
/// <summary>
/// Razor2 的摘要说明
/// </summary>
public class Razor2 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";//1.修改为html
//2.调用封装的方法ParseRazor
string html= RPcshtmlHelper.ParseRazor(context, "~/Razor2.cshtml",null);
//3.将转化过的模板内容输入到浏览器
context.Response.Write(html);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}