萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Razor 模板引擎呼叫外部方法:@using 引入命名空間與 RawString 輸出 HTML

Razor 模板中呼叫 C# 靜態方法:封裝 HTML 產生邏輯

Razor (`.cshtml`) 支援直接呼叫 C# 方法,配合 `RawString` (或 `HtmlString`) 輸出未編碼 HTML,可將重複的標籤產生邏輯封裝為可重用方法。

1. Razor 解析輔助類

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 套件
    }
}

2. 在 .cshtml 中引用外部方法

@using WebTest1.RazorDemo  @* 引入方法所在命名空間 *@
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" /><title>Demo</title></head>
<body>
  @RazorTest.Test1()<br />
  @RazorTest.Test2()
</body>
</html>

3. 封裝 HTML 產生方法:回傳 RawString 避免雙重編碼

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()";
}

4. Handler 中呼叫解析並輸出

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/html";
    string html = RazorHelper.ParseRazor(context, "~/RazorDemo/Razor2.cshtml", null);
    context.Response.Write(html);
}

5. 進階:Model 綁定與條件屬性

// 傳入 Model
bool gender = true;
string html = RazorHelper.ParseRazor(context, "~/RazorDemo/Edit.cshtml", new { Gender = gender });

// Edit.cshtml - 使用括號改變優先順序
<input type="checkbox" @(Model.Gender ? "checked" : "") />

關鍵注意事項

  • XSS 防護:輸出使用者輸入內容時,**務必**使用 `@Model.Content` (自動 HTML 編碼) 或 `HttpUtility.HtmlEncode`。僅信任的靜態/後端產生 HTML 才用 `HtmlString`/`RawString`。
  • 命名空間管理:在 `~/Views/Web.config` (MVC) 或 `_ViewImports.cshtml` (Core) 統一 `@using`,避免每個檔案重複引入。
  • 效能:`RazorEngine` 編譯緩存依賴 `cacheKey`,包含檔案修改時間可實現熱重載。
  • 非同步:RazorEngine 不支援 async 方法,複雜邏輯請在 Controller/Service 準備好 Model 再傳入。

ASP.NET Core 原生 Razor Pages / ViewComponent

Core 專案**不需**手動解析 `.cshtml`,直接:

  • Razor Pages:`return Page()` 自動渲染對應 `.cshtml`。
  • ViewComponent:`@await Component.InvokeAsync("Widget", new { id = 1 })` 封裝複雜邏輯與視圖。
  • TagHelper:`` 擴充 HTML 標籤。

適用場景: 傳統 ASP.NET (Web Forms/MVC 5) 整合 RazorEngine 產生郵件模板、PDF HTML、靜態頁面生成;Core 專案請使用原生架構。

copyright © 萬盛學電腦網 all rights reserved