1、通过nuget安装RazorEngine
Razor引擎下载地址:http://github.com/Antaris/RazorEngine
2、来看代码
后台部分:
string fullPath = AppDomain.CurrentDomain.BaseDirectory+@"/Views/MyView.cshtml";//拿到cshtml文件路径
string cshtml = File.ReadAllText(fullPath);//得到文件内容
string cache = cache + EncrypHelper.MD5(cshtml);
string myhtml = Razor.Parse(cshtml, new {name="tom"}, null, cache)
再看一下页面:
<!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>
<ul>@Model.name</ul>
</body>
</html>
@Model.属性 可以直接使用。
也可以指定类型Razor.Parse<T>(text, model);
看到有文章说Razor.Parse每次都会将动态编译的东西保存在内存中,参考:https://stackoverflow.com/questions/12301515/razorengine-memory-usage
所以,有下面解决办法:
- 加上cache
- 不用用3.0
- 用Precompiling Templates方法,参考:https://razorengine.codeplex.com/wikipage?title=Quick Start Guide&referringTitle=Documentation