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

时间:2008-09-07 13:25:48  来源:互联网  作者|记者:不详  浏览:2  大小:【】【】【
捌度空间导读:在ASP.NET MVC的一个开源项目MvcContrib中,为我们提供了几个视图引擎,例如NVelocity, Brail, NHaml, ...

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

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

<!DOCTYPE html PUBLIC " /pre>

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 {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); } #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 }

public class SimpleViewLocator : ViewLocator    {        public SimpleViewLocator()        {            base.ViewLocationFormats = new string[] { "~ iews/{1}/{0}.htm",                                                      "~ iews/{1}/{0}.html",                                                      "~ iews d/{0}.htm",                                                      "~ iews d/{0}.html"            };            base.MasterLocationFormats = new string[] { "" };        }    }

public class SimpleControllerFactory : DefaultControllerFactory    {        protected override IController CreateController(RequestContext                                requestContext, string controllerName)        {            Controller controller = (Controller)base.CreateController                              (requestContext, controllerName);            controller.ViewEngine = new SimpleViewEngine();                      //修改默认的视图引擎为我们刚才创建的视图引擎            return controller;        }    }



引用地址:

相关文章

最新文章

热点文章

推荐文章