Razor (`.cshtml`) 支援直接呼叫 C# 方法,配合 `RawString` (或 `HtmlString`) 輸出未編碼 HTML,可將重複的標籤產生邏輯封裝為可重用方法。
public static class RazorHelper
{
public static string ParseRazor(HttpContext context, string cshtmlVirtualPath, object model)
{
string fullPath = context.Server.MapPath(cshtmlVirtualPath);
string cshtml = File.ReadAllText(fullPath);
string cacheName = fullPath + File.GetLastWriteTime(fullPath).Ticks; // 檔案變更自動失效
return Razor.Parse(cshtml, model, cacheName); // 需引用 RazorEngine 套件
}
}
@using WebTest1.RazorDemo @* 引入方法所在命名空間 *@
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /><title>Demo</title></head>
<body>
@RazorTest.Test1()<br />
@RazorTest.Test2()
</body>
</html>
using System.Text;
using System.Web; // HtmlString / IHtmlString
public static class RazorTest
{
// 產生 CheckBox HTML
public static IHtmlString CheckBox(string name, string id, bool isChecked)
{
var sb = new StringBuilder();
sb.Append("");
return new HtmlString(sb.ToString()); // 標記為已編碼,Razor 不會再次編碼
}
// 簡單測試方法
public static string Test1() => "Hello from Test1()";
public static string Test2() => "Hello from Test2()";
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string html = RazorHelper.ParseRazor(context, "~/RazorDemo/Razor2.cshtml", null);
context.Response.Write(html);
}
// 傳入 Model
bool gender = true;
string html = RazorHelper.ParseRazor(context, "~/RazorDemo/Edit.cshtml", new { Gender = gender });
// Edit.cshtml - 使用括號改變優先順序
<input type="checkbox" @(Model.Gender ? "checked" : "") />
Core 專案**不需**手動解析 `.cshtml`,直接:
適用場景: 傳統 ASP.NET (Web Forms/MVC 5) 整合 RazorEngine 產生郵件模板、PDF HTML、靜態頁面生成;Core 專案請使用原生架構。