使用 Razor 引擎的標準流程包含三個步驟:讀取 .cshtml 檔案 → 解析模板並指定快取名稱 → 輸出 HTML。為遵循 DRY 原則,將此流程封裝為 RazorHelper 靜態類別。
public 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);
string html = Razor.Parse(cshtml, model, cacheName);
return html;
}
}
@using WebTest1.RazorDemo;<!-- 包含外部方法的類別命名空間 -->
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
@RazorTest.test1()<br />
@RazorTest.test2()
</body>
</html>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string html = RazorHelper.ParseRazor(context, @"~/Razordemo/Razor2.cshtml", null);
context.Response.Write(html);
}
痛點:直接在模板中處理 CheckBox 狀態導致程式碼混亂
<input type="checkbox" @(Model.Gender?"checked":"") /> <!-- 需加括號改變優先級,否則編譯器誤判為字串 -->
解決方案:封裝 CheckBox 靜態方法回傳 RawString
public static RawString CheckBox(string name, string id, bool isChecked)
{
StringBuilder sb = new StringBuilder();
sb.Append("<input type='checkbox' id='").Append(id).Append("' ")
.Append("name='").Append(name).Append("' ");
if (isChecked) sb.Append("checked");
sb.Append("/>");
return new RawString(sb.ToString());
}
string html = RazorHelper.ParseRazor(context, @"~/Razordemo/Razor2.cshtml", null); context.Response.Write(html);
@using WebTest1.RazorDemo;
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
@RazorTest.CheckBox("apple","apple",true)
</body>
</html>
此模式特別適合需要大量動態表單元素、條件式渲染或重複 UI 結構的場景,能顯著提升 Razor 模板的工程化程度。