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

ASP.NET MVC 實作自訂視圖引擎

     編輯:關於ASP.NET

MvcContrib 提供 NVelocity、Brail、NHaml、XSLT 等視圖引擎。若要自行實作視圖引擎,從 Controller.RenderView() 切入。

原理分析

protected virtual void RenderView(string viewName, string masterName, object viewData)
{
    ViewContext viewContext = new ViewContext(
        ControllerContext, viewName, masterName, viewData, TempData);
    ViewEngine.RenderView(viewContext);
}

RenderView 將參數封裝為 ViewContext,交由 ViewEngine.RenderView 處理。預設引擎為 WebFormsViewEngine。自訂引擎需實作 IViewEngine 介面。

範本範例 (HTML)

<!DOCTYPE html ...>
<html>
<head><title>自訂視圖引擎示例</title></head>
<body>
<h1>{$ViewData.Title}</h1>
<p>{$ViewData.Message}</p>
<p>{$ViewData.FruitStrings[1]}</p>
<p>{$ViewData.FruitObjects[1].Name}</p>
<p>{$UNDEFINED}</p>
</body>
</html>

SimpleViewEngine 實作

public class SimpleViewEngine : IViewEngine
{
    IViewLocator _viewLocator = null;

    public void RenderView(ViewContext viewContext)
    {
        string viewLocation = ViewLocator.GetViewLocation(viewContext, viewContext.ViewName);
        if (string.IsNullOrEmpty(viewLocation))
            throw new InvalidOperationException(string.Format("View {0} could not be found.", viewContext.ViewName));

        string viewPath = viewContext.HttpContext.Request.MapPath(viewLocation);
        string viewTemplate = File.ReadAllText(viewPath);

        IRenderer renderer = new PrintRenderer();
        viewTemplate = renderer.Render(viewTemplate, viewContext);
        viewContext.HttpContext.Response.Write(viewTemplate);
    }

    public IViewLocator ViewLocator
    {
        get
        {
            if (this._viewLocator == null)
                this._viewLocator = new SimpleViewLocator();
            return this._viewLocator;
        }
        set { this._viewLocator = value; }
    }
}

核心邏輯:定位視圖檔案 → 讀取模板 → 解析渲染 → 輸出回應。需另行實作 IViewLocator 與 IRenderer。

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