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 介面。
<!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>
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。