首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET Razor 模板引擎呼叫外部方法完整實戰指南

     編輯:ASP.NET 基礎

Razor 模板引擎核心工作流程

使用 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;
    }
}

在 .cshtml 中呼叫外部方法三步驟

步驟 1:引用命名空間

@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>

步驟 2:一般處理程式解析模板

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

步驟 3:封裝複雜 UI 邏輯為可重用方法

痛點:直接在模板中處理 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);

.cshtml 模板

@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>

架構優勢總結

  • 關注點分離:HTML 結構與 UI 邏輯分離
  • 可測試性:外部方法可獨立單元測試
  • 重用性:CheckBox 等 UI 元件跨模板重用
  • 可維護性:複雜渲染邏輯集中管理,模板保持簡潔

此模式特別適合需要大量動態表單元素、條件式渲染或重複 UI 結構的場景,能顯著提升 Razor 模板的工程化程度。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved