(翻译)为你的MVC应用程序创建自定义视图引擎
Creating your own MVC View Engine For MVC Application
原文鏈接:http://www.codeproject.com/Articles/294297/Creating-your-own-MVC-View-Engine-into-MVC-Applica
簡(jiǎn)介(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視圖引擎。對(duì)于Razor來(lái)說(shuō),其使用的頁(yè)面文件以.cshtml或者.vbhtml作為后綴。而Web Form 視圖引擎則以aspx文件作為界面呈現(xiàn)。
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框架同樣支持自定義視圖引擎。到目前為止,已經(jīng)有若干開(kāi)源的Web Form視圖引擎可供選擇,比如Nhaml(全稱為:pronounced enamel)、spark, Brail, nVelocity等。不同的視圖引擎可以讓你以不同的方式編寫(xiě)你的用戶界面。
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項(xiàng)目中,支持同時(shí)使用多個(gè)視圖引擎用于頁(yè)面渲染。為了做到這一點(diǎn),只需要在global.aspx注冊(cè)這些引擎即可。
自定義視圖引擎(Custom View Engines):
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.
創(chuàng)建屬于你的視圖引擎非常簡(jiǎn)單。在這之前,你需要確定的問(wèn)題是以何種方式編寫(xiě)你的視圖文件。
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.
自定義視圖引擎最簡(jiǎn)單的方式就是繼承VirtualPathProviderViewEngine抽象類并實(shí)現(xiàn)必需的方法。VirtualPathProviderViewEngine類已經(jīng)幫你實(shí)現(xiàn)了定位及緩存視圖文件的功能。(譯者注:VirtualPathProviderViewEngine 抽象類實(shí)現(xiàn)了IViewEngine接口。直接實(shí)現(xiàn)IViewEngine接口則需要覆寫(xiě)FindView 及 FindPartialView等方法)
Now take a simple example of MyViewEngine it will return simple view.
下面讓我們以一個(gè)簡(jiǎn)單的MyViewEngine來(lái)進(jìn)行說(shuō)明。最終該視圖引擎會(huì)渲染一個(gè)簡(jiǎn)單的視圖文件。
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:
首先我們創(chuàng)建一個(gè)空的MVC項(xiàng)目,然后添加一個(gè) MyViewEngine.cs 類文件并讓其繼承自 VirtualPathProviderViewEngine抽象類。覆寫(xiě)createview 和 createpartialview 方法。二者均返回一個(gè)MyView的實(shí)例。代碼如下:
public class MyViewEngine : VirtualPathProviderViewEngine{public MyViewEngine(){// Define the location of the View filethis.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.
注意在構(gòu)造函數(shù)中,我們?cè)O(shè)置了抽象基類的兩個(gè)屬性。這兩個(gè)屬性標(biāo)識(shí)了視圖引擎到何處去匹配我們的View和PartialView。其中,第一個(gè)參數(shù)代表了controller,第二個(gè)參數(shù)則代表action。
Now, create another class named MyView which implements IView interface. This class actually renders the view. MyView class code looks like below:
接下來(lái)創(chuàng)建MyView類,使其繼承自IView接口。真正的渲染視圖文件的工作將在該類中完成。其完整代碼如下:
public class MyView : IView{private string _viewPhysicalPath;public MyView(string ViewPhysicalPath){_viewPhysicalPath = ViewPhysicalPath;}#region IView Memberspublic void Render(ViewContext viewContext, System.IO.TextWriter writer){//Load Filestring rawcontents = File.ReadAllText(_viewPhysicalPath);//Perform Replacementsstring parsedcontents = Parse(rawcontents, viewContext.ViewData);writer.Write(parsedcontents);}#endregionpublic 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方法首先加載視圖文件,然后結(jié)合相關(guān)數(shù)據(jù)進(jìn)行解析。最后將解析后的結(jié)果輸出至文本流。
Before use, custom view engine is required to register view engine into Global.asax file using the following code:
在實(shí)際使用自定義視圖引擎之前,需要我們用以下代碼在Global.asax文件中進(jìn)行注冊(cè):
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:
現(xiàn)在我們?cè)贑ontroller目錄下創(chuàng)建一個(gè)名為MyViewController的控制器,在該controller中定義一個(gè)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:
接下來(lái)在 View/MyView/ 目錄下,新建一個(gè)簡(jiǎn)單的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.
現(xiàn)在運(yùn)行你的應(yīng)用程序,修改地址欄中URL為:/MyView/Index,你將會(huì)在瀏覽器中看到"Hello World!"的輸出。也就是說(shuō),MyView類加載了Index.myview文件,替換其中的{message}標(biāo)簽為"Hello World!",將其渲染成為Html頁(yè)面。
結(jié)論(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.
從上述自定義視圖引擎的過(guò)程可以看出:MVC開(kāi)發(fā)團(tuán)隊(duì)做了大量牛逼的工作,提供了一個(gè)高度靈活、高度可擴(kuò)展的開(kāi)發(fā)框架,以適應(yīng)不同場(chǎng)景下的應(yīng)用程序開(kāi)發(fā)。
版權(quán)(License):
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
本文及其附帶的源代碼文件,均遵從CPOL開(kāi)源協(xié)議。
轉(zhuǎn)載于:https://www.cnblogs.com/mcmurphy/p/3346816.html
總結(jié)
以上是生活随笔為你收集整理的(翻译)为你的MVC应用程序创建自定义视图引擎的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ibatis学习笔记(三)java实体跟
- 下一篇: s3c2440移植MQTT