在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);
ViewEngineRenderView(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://wwwworg/TR/xhtml/DTD/xhtmltransitionaldtd>
<html xmlns=http://wwwworg//xhtml>
http://wwwworg//xhtml >
<head>
<title>自定义视图引擎示例</title>
</head>
<body>
<h>{$ViewDataTitle}</h>
<p>{$ViewDataMessage}</p>
<p>The following fruit is part of a string array: {$ViewDataFruitStrings[]}</p>
<p>The following fruit is part of an object array: {$ViewDataFruitObjects[]Name}</p>
<p>Heres 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 = ViewLocatorGetViewLocation
(viewContext viewContextViewName);
if (stringIsNullOrEmpty(viewLocation))
{
throw new InvalidOperationException(stringFormat
(View {} could not be found viewContextViewName));
}
string viewPath = viewContextHttpContextRequestMapPath(viewLocation);
string viewTemplate = FileReadAllText(viewPath);
//以下为模板解析
IRenderer renderer = new PrintRenderer();
viewTemplate = rendererRender(viewTemplate viewContext);
viewContextHttpContextResponseWrite(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
}
[] [] []