Creating your own MVC View Engine For MVC Applicationhtml
原文連接:http://www.codeproject.com/Articles/294297/Creating-your-own-MVC-View-Engine-into-MVC-Applicaweb
簡介(Introduction):瀏覽器
The View engines used in ASP.NET MVC Framework are the Razor View Engine and Web Form View Engine. Razor View engine used .cshtml and .vbhtml. While Web Form View Engine used .aspx to design the layout of the user interface.緩存
微軟的ASP.NET MVC框架中使用的視圖引擎通常有二:Razor和Web Form視圖引擎。對於Razor來講,其使用的頁面文件以.cshtml或者.vbhtml做爲後綴。而Web Form 視圖引擎則以aspx文件做爲界面呈現。app
The ASP.NET MVC Framework was designed to support alternative view engines and there are already several open source alternatives to the web forms view engine like Nhaml (pronounced enamel), spark, Brail, nVelocity. The different View Engines enable to write your view in different ways.框架
另外一方面,ASP.NET MVC框架一樣支持自定義視圖引擎。到目前爲止,已經有若干開源的Web Form視圖引擎可供選擇,好比Nhaml(全稱爲:pronounced enamel)、spark, Brail, nVelocity等。不一樣的視圖引擎可讓你以不一樣的方式編寫你的用戶界面。ide
It is possible to use multiple view engines used in one MVC application. For that, it is required to registering multiple engines in the global.aspx file.函數
在微軟的MVC項目中,支持同時使用多個視圖引擎用於頁面渲染。爲了作到這一點,只須要在global.aspx註冊這些引擎便可。flex
自定義視圖引擎(Custom View Engines):ui
It is very simple to create your own custom view engine. When you create your own view engine, you have to just think about how you want to write your views.
建立屬於你的視圖引擎很是簡單。在這以前,你須要肯定的問題是以何種方式編寫你的視圖文件。
The easiest approach to create custom view engine is just derive a new view engine from abstract VirtualPathProviderViewEngine Class. This base class can take care of the all low-level mechanics of finding and caching views.
自定義視圖引擎最簡單的方式就是繼承VirtualPathProviderViewEngine抽象類並實現必需的方法。VirtualPathProviderViewEngine類已經幫你實現了定位及緩存視圖文件的功能。(譯者注:VirtualPathProviderViewEngine 抽象類實現了IViewEngine接口。直接實現IViewEngine接口則須要覆寫FindView 及 FindPartialView等方法)
Now take a simple example of MyViewEngine it will return simple view.
下面讓咱們以一個簡單的MyViewEngine來進行說明。最終該視圖引擎會渲染一個簡單的視圖文件。
The first step is to create an empty MVC application. Then add a class file named MyViewEngine.cs and inherit that class from VirtualPathProviderViewEngine and override createview and createpartialview methods. These methods return an instance of the MYView Class. Your class will look like below:
首先咱們建立一個空的MVC項目,而後添加一個 MyViewEngine.cs 類文件並讓其繼承自 VirtualPathProviderViewEngine抽象類。覆寫createview 和 createpartialview 方法。兩者均返回一個MyView的實例。代碼以下:
public class MyViewEngine : VirtualPathProviderViewEngine { public MyViewEngine() { // Define the location of the View file this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview" }; this.PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview" }; } protected override IView CreatePartialView (ControllerContext controllerContext, string partialPath) { var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath); return new MyView(physicalpath); } protected override IView CreateView (ControllerContext controllerContext, string viewPath, string masterPath) { var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath); return new MyView(physicalpath); } }
Note that in the constructor, we set two properties of the base class. These properties indicate where the view engine should search to find a matching view or partial view.The parameter {1} represents the name of the controller and the parameter {0} represents the name of the action.
注意在構造函數中,咱們設置了抽象基類的兩個屬性。這兩個屬性標識了視圖引擎到何處去匹配咱們的View和PartialView。其中,第一個參數表明了controller,第二個參數則表明action。
Now, create another class named MyView which implements IView interface. This class actually renders the view. MyView class code looks like below:
接下來建立MyView類,使其繼承自IView接口。真正的渲染視圖文件的工做將在該類中完成。其完整代碼以下:
public class MyView : IView { private string _viewPhysicalPath; public MyView(string ViewPhysicalPath) { _viewPhysicalPath = ViewPhysicalPath; } #region IView Members public void Render(ViewContext viewContext, System.IO.TextWriter writer) { //Load File string rawcontents = File.ReadAllText(_viewPhysicalPath); //Perform Replacements string parsedcontents = Parse(rawcontents, viewContext.ViewData); writer.Write(parsedcontents); } #endregion public string Parse(string contents, ViewDataDictionary viewdata) { return Regex.Replace(contents, "\\{(.+)\\}", m => GetMatch(m,viewdata)); } public virtual string GetMatch(Match m, ViewDataDictionary viewdata) { if (m.Success) { string key = m.Result("$1"); if (viewdata.ContainsKey(key)) { return viewdata[key].ToString(); } } return string.Empty; } }
Render method of the class loads the view files and injects view data into the view, and writes that result into a text writer.
MyView類中的Render方法首先加載視圖文件,而後結合相關數據進行解析。最後將解析後的結果輸出至文本流。
Before use, custom view engine is required to register view engine into Global.asax file using the following code:
在實際使用自定義視圖引擎以前,須要咱們用如下代碼在Global.asax文件中進行註冊:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); //Register your View Engine Here. ViewEngines.Engines.Add(new MyViewEngine()); }
Now create a controller file into controller folder named myViewController and define index action into the controller. Your controller class will look like below:
如今咱們在Controller目錄下建立一個名爲MyViewController的控制器,在該controller中定義一個action:Index。代碼以下:
public class MyViewController : Controller { // // GET: /myView/ public ActionResult Index() { ViewData["Message"] = "Hello World!"; return View(); } }
Now add the simple HTML File into View/MyView/ folder and give the name of the file like index.myview. Your view file markup looks like below:
接下來在 View/MyView/ 目錄下,新建一個簡單的HTML文件,修更名稱爲Index.myview,其最終代碼以下:
<html>
<head>
<title>Index MyView </title>
</head>
<body>{message}
</body>
</html>
Now run the application and type URL /MyView /Index. You will get output of the Hello World! into the browser. The MyView class loads the index.myview file and replaces {message} with hello world! and renders the HTML Page.
如今運行你的應用程序,修改地址欄中URL爲:/MyView/Index,你將會在瀏覽器中看到"Hello World!"的輸出。也就是說,MyView類加載了Index.myview文件,替換其中的{message}標籤爲"Hello World!",將其渲染成爲Html頁面。
結論(Conclusion):
After developing Custom View Engine, we can say that MVC team has done an awesome job at providing a very flexible framework for us to tweak and customize it so it fits our applications.
從上述自定義視圖引擎的過程能夠看出:MVC開發團隊作了大量牛逼的工做,提供了一個高度靈活、高度可擴展的開發框架,以適應不一樣場景下的應用程序開發。
版權(License):
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
本文及其附帶的源代碼文件,均聽從CPOL開源協議。