(翻译)为你的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
简介(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文件作为界面呈现。
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等。不同的视图引擎可以让你以不同的方式编写你的用户界面。
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注册这些引擎即可。
自定义视图引擎(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.
创建属于你的视图引擎非常简单。在这之前,你需要确定的问题是以何种方式编写你的视图文件。
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开源协议。