In MvcContrib, an open-source project of ASP. net mvc, several view engines are provided for us, such as NVelocity, Brail, NHaml, and XSLT. So what should we do if we want to implement our own view engine in ASP. net mvc?
We know that the rendering view is implemented in the Controller by passing the view name and data to the RenderView () method. Okay, let's start from here. Let's take a look at the source code of ASP. net mvc and see how the RenderView () method is implemented:
protected virtual void RenderView(string viewName, string masterName, object viewData) { ViewContext viewContext = new ViewContext(ControllerContext, viewName, masterName, viewData, TempData); ViewEngine.RenderView(viewContext);}// |
This is the source code of P2. P3 is slightly different and the principle is similar. From the code above, we can see that the RenderView () method in Controller mainly involves ControllerContext, viewName, masterName, viewData, tempData is encapsulated into ViewContext and passed to ViewEngine. renderView (viewContext ). Well, that's right. Here we want to implement the RenderView () method of ViewEngine.
ASP. net mvc provides a default view engine called WebFormsViewEngine. we can see from the name that this view engine uses ASP. NET web forms. Here, the template used by the view engine is implemented using HTML files. The simple template sample code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
Next we will start our implementation. First of all, there is no doubt that we need to create a ViewEngine and name it SimpleViewEngine. Note that ViewEngine must implement the IViewEngine interface:
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); // The following is the template resolution 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} |