虫虫技术在线--技术决定出路

当前位置: 首页 > 编程 > .net >

ASP.NET MVC实现自己的一个视图引擎

时间:2010-03-13 11:00来源:虫虫技术在线收集整理 作者:admin 点击:
在ASP.net MVC的一个开源项目MvcContrib中,为我们提供了几个视图引擎,例如NVelocity, Brail, NHaml, XSLT。那么如果我们想在ASP.NET MVC中实现我们自己的一个视图引擎,我们应该要怎么做呢? 我

在ASP.net MVC的一个开源项目MvcContrib中,为我们提供了几个视图引擎,例如NVelocity, Brail, NHaml, XSLT。那么如果我们想在ASP.NET MVC中实现我们自己的一个视图引擎,我们应该要怎么做呢?

我们知道呈现视图是在Controller中通过传递视图名和数据到RenderView()方法来实现的。好,我们就从这里下手。我们查看一下ASP.NET MVC的源代码,看看RenderView()这个方法是如何实现的:

  1. protected virtual void RenderView(string viewName, string  
  2. masterName, object viewData) {  
  3. ViewContext viewContext = new ViewContext(  
  4. ControllerContext, viewName, masterName, viewData, TempData);  
  5. ViewEngine.RenderView(viewContext);  
  6. }//  
  7.  

这是P2的源码,P3略有不同,原理差不多,从上面的代码我们可以看到,Controller中的RenderView()方法主要是将ControllerContext, viewName, masterName, viewData, TempData这一堆东西封装成ViewContext,然后把ViewContext传递给ViewEngine.RenderView(viewContext)。嗯,没错,我们这里要实现的就是ViewEngine的RenderView()方法。

ASP.NET MVC为我们提供了一个默认的视图引擎,这个视图引擎叫做:WebFormsViewEngine. 从名字就可以看出,这个视图引擎是使用ASP.NET web forms来呈现的。在这里,我们要实现的视图引擎所使用的模板用HTML文件吧,简单的模板示例代码如下:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
  2. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html XMLns=""http://www.w3.org/1999/xhtml""> 
  4. http://www.w3.org/1999/xhtml" >  
  5. <head>  
  6.   <title>自定义视图引擎示例</title>  
  7. </head>  
  8. <body>  
  9.   <h1>{$ViewData.Title}</h1>  
  10.   <p>{$ViewData.Message}</p>  
  11.   <p>The following fruit is part of a string array: {$ViewData.FruitStrings[1]}</p>  
  12.   <p>The following fruit is part of an object array: {$ViewData.FruitObjects[1].Name}</p>  
  13.   <p>Here's an undefined variable: {$UNDEFINED}</p>  
  14. </body>  
  15. < ml>  
  16.  
  17. 下面马上开始我们的实现。首先,毫无疑问的,我们要创建一个ViewEngine,就命名为 SimpleViewEngine 吧,注意哦,ViewEngine要实现IViewEngine接口:  
  18.  
  19. public class SimpleViewEngine : IViewEngine  
  20.   {  
  21.     #region Private members  
  22.     IViewLocator _viewLocator = null;  
  23.     #endregion  
  24.     #region IViewEngine Members : RenderView()  
  25.     public void RenderView(ViewContext viewContext)  
  26.     {  
  27.       string viewLocation = ViewLocator.GetViewLocation  
  28.                  (viewContext, viewContext.ViewName);  
  29.       if (string.IsNullOrEmpty(viewLocation))  
  30.       {  
  31.         throw new InvalidOperationException(string.Format  
  32.           ("View {0} could not be found.",         viewContext.ViewName));  
  33.       }  
  34.       string viewPath = viewContext.HttpContext.Request.MapPath(viewLocation);  
  35.       string viewTemplate = File.ReadAllText(viewPath);  
  36.       //以下为模板解析  
  37.       IRenderer renderer = new PrintRenderer();  
  38.       viewTemplate = renderer.Render(viewTemplate, viewContext);  
  39.       viewContext.HttpContext.Response.Write(viewTemplate);  
  40.     }  
  41.     #endregion  
  42.     #region Public properties : ViewLocator  
  43.     public IViewLocator ViewLocator  
  44.     {  
  45.       get  
  46.       {  
  47.         if (this._viewLocator == null)  
  48.         {  
  49.           this._viewLocator = new SimpleViewLocator();  
  50.         }  
  51.         return this._viewLocator;  
  52.       }  
  53.       set  
  54.       {  
  55.         this._viewLocator = value;  
  56.       }  
  57.     }  
  58.     #endregion  
  59.   }  
  60.  


在这里实现了IViewEngine接口提供的RenderView()方法,这里要提供一个ViewLocator的属性。ViewLocator的主要就是根据控制器中传来的视图名,进行视图的定位。在RenderView()方法中首先获取视图的路径,然后把视图模板读进来,最后进行模板的解析然后输出。

我们再来看一下ViewLocator是如何实现的。他是IViewLocator类型的,也就是说SimpleViewLocator实现了IViewLocator接口。SimpleViewLocator的实现代码如下:

  1. public class SimpleViewLocator : ViewLocator  
  2.   {  
  3.     public SimpleViewLocator()  
  4.     {  
  5.       base.ViewLocationFormats = new string[] { "~ iews/{1}/{0}.htm",  
  6.                            "~ iews/{1}/{0}.html",  
  7.                            "~ iews d/{0}.htm",  
  8.                            "~ iews d/{0}.html"  
  9.       };  
  10.       base.MasterLocationFormats = new string[] { "" };  
  11.     }  
  12.   }  
  13.  

我们的SimpleViewLocator 是继承自ASP.net MVC的ViewLocator类,而ViewLocator则是实现了IViewLocator接口的。由于ViewLocator已经为了完成了全部的工作,这里我们只需修改下他的ViewLocationFormats 来使用我们自己的模板文件就可以了。

我们再来看一下类图,那就更加清楚了:


注:关于模板解析的部分代码这里就不说了,不在讨论范围内,可以自己下载代码来看。

现在我们基本完成了我们的视图引擎,那么如何让ASP.NET MVC不要使用默认的Web forms视图引擎,而使用我们自定义的视图引擎呢?

在ASP.NET MVC中,所有的请求都是通过一个工厂类来创建Controller实例的,这个工厂类必须实现IControllerFactory 接口。默认的实现该接口的工厂类是DefaultControllerFactory。这个工厂类就是我们修改默认的视图引擎为我们的视图引擎的入口点。为了方便,我们创建一个继承自DefaultControllerFactory的SimpleControllerFactory :

  1. public class SimpleControllerFactory : DefaultControllerFactory  
  2.   {  
  3.     protected override IController CreateController(RequestContext  
  4.                 requestContext, string controllerName)  
  5.     {  
  6.       Controller controller = (Controller)base.CreateController  
  7.                (requestContext, controllerName);  
  8.       controller.ViewEngine = new SimpleViewEngine();  
  9.            //修改默认的视图引擎为我们刚才创建的视图引擎  
  10.       return controller;  
  11.     }  
  12.   }  
  13.  

这里只要修改controller.ViewEngine为我们自定义的ViewEngine就可以了.最终的类图大概如下:


要使我们创建的控制器工厂类SimpleControllerFactory 成为默认的控制器工厂类,我们必须在Global.asax.cs中的Application_Start 事件中添加如下代码:ControllerBuilder.Current.SetControllerFactory(typeof(SimpleControllerFactory));

到这里,我们已经完成了我们自己的视图引擎。

在ASP.NET MVC中实现自定义的视图引擎是很简单的,难点在于模板的解析,具体大家可以研究MvcContrib中的四个视图引擎的代码。最近要对模板引擎进行研究,大家有什么其他优秀的、成熟的、开源的模板引擎,麻烦给小弟推荐一下,先谢了。


 

(责任编辑:admin)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
推荐内容