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 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.

注意在构造函数中,我们设置了抽象基类的两个属性。这两个属性标识了视图引擎到何处去匹配我们的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 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方法首先加载视图文件,然后结合相关数据进行解析。最后将解析后的结果输出至文本流。

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开源协议。

转载于:https://www.cnblogs.com/mcmurphy/p/3346816.html

(翻译)为你的MVC应用程序创建自定义视图引擎相关推荐

  1. [ASP.NET MVC2 系列] ASP.NET MVC 之如何创建自定义路由约束

     [ASP.NET MVC2 系列]      [ASP.NET MVC2 系列] ASP.Net MVC教程之<在15分钟内用ASP.Net MVC创建一个电影数据库应用程序>      ...

  2. [翻译:ASP.NET MVC 教程]理解模型、视图和控制器

    本篇教程为你提供了ASP.NET MVC的模型.视图和控制器的高级概述.换句话说,即本文向你解释了在ASP.NET MVC中"M"."V"和"C&qu ...

  3. 如何在Google Chrome中为扩展程序创建自定义键盘快捷键

    Geeks love keyboard shortcuts-they're often faster than clicking everything with your mouse. We've p ...

  4. MVC学习三:Razor视图引擎

    1.Razor视图引擎,主要是把View的HTML代码编译到View视图类对象中 转载于:https://www.cnblogs.com/WarBlog/p/7132611.html

  5. ASP.NET MVC 最好的视图引擎是什么?

    在ASP.NET Core MVC应用程序中,视图引擎(view engine)负责处理发送给客户端的内容.MVC框架中默认的视图引擎称为Razor,用来为HTML文件添加注释说明并将这些动态内容插入 ...

  6. ASP.NET MVC (一、控制器与视图)

    目录 前言: 1.MVC简介 2.项目创建:(这里使用工具为:Visual Studio 2019) 2.1.文件夹与文件夹介绍: 3.控制器 3.1.添加控制器 3.2.添加视图层 3.3.修改默认 ...

  7. ASP.NET MVC Razor视图引擎

    本篇文章我们一起来讨论ASP.NET MVC框架中的Razor视图引擎.主要包含以下内容: Razor简介 Razor语法 Razor如何呈现页面 布局页(Layout) Razor简介 Razor是 ...

  8. ASP.NET MVC:实现我们自己的视图引擎

    在ASP.NET MVC的一个开源项目MvcContrib中,为我们提供了几个视图引擎,例如NVelocity, Brail, NHaml, XSLT.那么如果我们想在ASP.NET MVC中实现我们 ...

  9. 一步一步学习ASP.NET MVC 1.0创建NerdDinner 范例程序 - 强烈推荐!!!

    一步一步学习ASP.NET MVC 1.0创建NerdDinner 范例程序 本文根据<Professional ASP.NET MVC 1.0>中微软牛人Scott Guthrie 提供 ...

最新文章

  1. 自动驾驶中常用的四类机器学习算法
  2. 二层交换配置完ping失败_设置完端口聚合之后就ping不通了!!!
  3. 分类模型的评估方法-正确率(Accuracy)
  4. 自然人税收管理系统扣缴客户端服务器超时,“自然人税收管理系统”扣缴客户端常见问题十问十答...
  5. PCB板材结构介绍(z)
  6. [渝粤教育] 西南科技大学 电子产品制造工艺 在线考试复习资料
  7. ESXI忘记密码怎么办?
  8. Linux shell逐行读取文件的方法-比较
  9. python模块名不规范如何导入_如何强制Python的“导入”将名称视为模块,而不是函数?...
  10. 【LOJ】#3123. 「CTS2019 | CTSC2019」重复
  11. 《C程序设计新思维》一第6章 玩转指针6.1 自动、静态和手工内存
  12. 新浪的wap网站,发现原来我们的head存在着这样的差异
  13. 爱创课堂每日一题第四十八天- html5有哪些新特性、移除了那些元素?
  14. 每日自增字段mysql_2020-11-05 触发器实现mysql每日自增字段
  15. 要马儿跑,又要马儿不吃草?聊聊联邦学习与分布式机器学习
  16. H. Zebras and Ocelots -ICPC North Central NA Contest 2017
  17. 人工智能--启发性信息和估价函数
  18. “新基建”下的智慧城轨:城轨为“体” 智慧为“用”
  19. 1114 计算营业额
  20. 积分商城该如何帮助商家盈利

热门文章

  1. 深度历险:Redis 内存模型详解
  2. Linux:shell脚本中实现变量自增的几种方式
  3. Andriod --- JetPack (三):ViewModel 的诞生
  4. html hover图片效果,CSS第9款:Imagehover.css 纯CSS打造的图片悬停效果
  5. 高斯-赛得尔迭代式 c++_高斯混合模型(Gaussian Mixture Model)与EM算法原理(一)
  6. 语言用加法实现加饭运算_「编程之美」用C语言实现状态机(超实用)
  7. 夏天雷雨天机房断电了,该怎么办?,叫你几招紧急应对方法
  8. github 删除分支_Github新手入门指南
  9. 去掉状态条并全屏_一个人住180㎡,大大的落地窗,足够的收纳,简洁又舒适,宅在家是她最享受的状态!...
  10. 在java中重写方法应遵循规则的包括_Java面试题集合篇二