在ASPNET MVC的一個開源項目MvcContrib中為我們提供了幾個視圖引擎例如NVelocity Brail NHaml XSLT那麼如果我們想在ASPNET MVC中實現我們自己的一個視圖引擎我們應該要怎麼做呢?
我們知道呈現視圖是在Controller中通過傳遞視圖名和數據到RenderView()方法來實現的好我們就從這裡下手我們查看一下ASPNET MVC的源代碼看看RenderView()這個方法是如何實現的
protected virtual void RenderView(string viewName
string
masterName
object viewData) {
ViewContext viewContext = new ViewContext(
ControllerContext
viewName
masterName
viewData
TempData);
ViewEngine
RenderView(viewContext);
}//
這是P的源碼P略有不同原理差不多從上面的代碼我們可以看到Controller中的RenderView()方法主要是將ControllerContext viewName masterName viewData TempData這一堆東西封裝成ViewContext然後把ViewContext傳遞給ViewEngineRenderView(viewContext)嗯沒錯我們這裡要實現的就是ViewEngine的RenderView()方法
ASPNET MVC為我們提供了一個默認的視圖引擎這個視圖引擎叫做WebFormsViewEngine 從名字就可以看出這個視圖引擎是使用ASPNET web forms來呈現的在這裡我們要實現的視圖引擎所使用的模板用HTML文件吧簡單的模板示例代碼如下
<!DOCTYPE html PUBLIC
//W
C//DTD XHTML
Transitional//EN
http://www
w
org/TR/xhtml
/DTD/xhtml
transitional
dtd
>
<html xmlns=
http://www
w
org/
/xhtml
>
http://www
w
org/
/xhtml
>
<head>
<title>自定義視圖引擎示例</title>
</head>
<body>
<h
>{$ViewData
Title}</h
>
<p>{$ViewData
Message}</p>
<p>The following fruit is part of a string array: {$ViewData
FruitStrings[
]}</p>
<p>The following fruit is part of an object array: {$ViewData
FruitObjects[
]
Name}</p>
<p>Here
s an undefined variable: {$UNDEFINED}</p>
</body>
< ml>
下面馬上開始我們的實現首先毫無疑問的我們要創建一個ViewEngine就命名為 SimpleViewEngine 吧注意哦ViewEngine要實現IViewEngine接口
public class SimpleViewEngine : IViewEngine
{
#region Private members
IViewLocator _viewLocator = null;
#endregion
#region IViewEngine Members : RenderView()
public void RenderView(ViewContext viewContext)
{
string viewLocation = ViewLocator
GetViewLocation
(viewContext
viewContext
ViewName);
if (string
IsNullOrEmpty(viewLocation))
{
throw new InvalidOperationException(string
Format
(
View {
} 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);
}
#endregion
#region Public properties : ViewLocator
public IViewLocator ViewLocator
{
get
{
if (this
_viewLocator == null)
{
this
_viewLocator = new SimpleViewLocator();
}
return this
_viewLocator;
}
set
{
this
_viewLocator = value;
}
}
#endregion
}
[] [] []
From:http://tw.wingwit.com/Article/program/net/201311/15013.html