(翻译)为你的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开源协议。
(翻译)为你的MVC应用程序创建自定义视图引擎的更多相关文章
- [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:为ASP.NET MVC应用程序创建更复杂的数据模型
这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第六篇:为ASP.NET MVC应用程序 ...
- 为ASP.NET MVC应用程序创建更复杂的数据模型
为ASP.NET MVC应用程序创建更复杂的数据模型 2014-05-07 18:27 by Bce, 282 阅读, 1 评论, 收藏, 编辑 这是微软官方教程Getting Started wit ...
- Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型
原文 Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型 原文地址:Creating an Entity Framework Data Model for an ...
- ASP.NET MVC自定义视图引擎ViewEngine 创建Model的专属视图
MVC内置的视图引擎有WebForm view engine和Razor view engine,当然也可以自定义视图引擎ViewEngine. 本文想针对某个Model,自定义该Model的专属视图 ...
- Asp.net MVC 移除不用的视图引擎
Asp.net MVC 默认提供两个视图引擎,分别为: WebFormViewEngine 和 RazorViewEngine.MVC在查找视图时,会按照指定的顺序进行查找.当我们的MVC程序未找到相 ...
- ASP.NET MVC扩展自定义视图引擎支持多模板&动态换肤skins机制
ASP.NET mvc的razor视图引擎是一个非常好的.NET MVC框架内置的视图引擎.一般情况我们使用.NET MVC框架为我们提供的这个Razor视图引擎就足够了.但是有时我们想在我们的项目支 ...
- ASP.NET MVC 扩展自定义视图引擎支持多模板&动态换肤skins机制
ASP.NET mvc的razor视图引擎是一个非常好的.NET MVC 框架内置的视图引擎.一般情况我们使用.NET MVC框架为我们提供的这个Razor视图引擎就足够了.但是有时我们想在我们的 ...
- 创建自定义视图在Android矩阵效果画布教程
介绍 下面是一个快速教程,教你如何在Android中创建自定义视图.自定义视图创建一个矩阵雨效果. 本教程发布在http://www.androidlearner.com/. 背景 下面是关于如何工作 ...
- 自定义视图引擎,实现MVC主题快速切换
一个网站的主题包括布局,色调,内容展示等,每种主题在某些方面应该或多或少不一样的,否则就不能称之为不同的主题了.每一个网站至少都有一个主题,我这里称之为默认主题,也就是我们平常开发设计网站时的一个固定 ...
随机推荐
- vim语法高亮不起作用解决
首先将vim更新为最新版yum -y install vim,并安装Vim的加强版vim-enhanced ,以安装支持彩色的组件 yum -y install vim-enhanced 接下来 ...
- <后会无期>经典影评
先说明是转载,任何不同意见请对原作者表达,楼主不作任何回应,楼主影商极低,楼主觉得这二十几年来看的最好的电影是<一代宗师>,楼主只是觉得这篇影评精彩才发布上来让更多的人看到.原作者意见和楼 ...
- AngularJS Eclipse——新手入门【翻译+整理】
原文地址 本文介绍如何安装和配置 AngularJS Eclipse.AngularJS Eclipse 插件是基于强大的 JavaScript 推断引擎(javascript inference e ...
- Dell U2913WM使用感受
21:9比例,本来想代替双屏的,一周用下来还是不适应,如何能弯成曲面就爽了.感觉最舒服的还是以前19寸5:4双屏,点距大. 还尝试在旁边立个23寸,看了15分钟就受不了,头晕. 漏光,还行. 加了个A ...
- go2shell的安装与修改默认terminal方法
go2shell的安装与修改默认terminal方法 1. 安装go2shell后,打开finder的application文件夹,找到go2shell 2. 按住command,用鼠标将go2s ...
- HL AsySocket 服务开发框架 - 业务逻辑层
一 概述 Socket服务只是提供一个网络传输服务. 业务逻辑层在整体架构中的位置在那里呢,如图: 网络层将解包后的消息包抛至业务逻辑层,业务逻辑层收到消息包后,解析消息类型,然后转入相应的处理流程处 ...
- 使用 jsErrLog 分析 js 报错
1. github 地址: https://github.com/Offbeatmammal/jsErrLog/tree/master/src 2. 在所有页面引入 jsErrLog,配置出错时打日志 ...
- Android表情功能
Android表情功能 标签(空格分隔): 未分类 转载自:android edittext插入表情(基于socket方式),并对文中不正确的内容进行整理和修正 [TOC] 涉及知识点: Androi ...
- [原创]自定义BaseAcitivity的实现,统一activity的UI风格样式
在开发过程中经常遇到多个activity是同一种样式类型的情况,如果分别对其进行UI的布局,不但比较繁琐,而且后续维护过程人力成本很高,不利于敏捷开发.解决的方案是采用抽象后的BaseActi ...
- 实现仿知乎的开场动画,图片zoomin的效果,实现原理,没加动效
知乎等应用的开场动画是:全屏显示一副图像,并以图像的中间为原点,实现放大(也就是zoomin)的动画,让等待的过程不再单调乏味. 最近不是很忙,因此想了下如何实现这种效果,方案是:采用调整imagev ...