(翻译)为你的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主题快速切换
一个网站的主题包括布局,色调,内容展示等,每种主题在某些方面应该或多或少不一样的,否则就不能称之为不同的主题了.每一个网站至少都有一个主题,我这里称之为默认主题,也就是我们平常开发设计网站时的一个固定 ...
随机推荐
- ubuntu 16.04 U盘多媒体不自动弹出
如下图: 设置 --> 详细信息 --> 可移动媒体 来自为知笔记(Wiz)
- 私有云android客户端2.1.2最新版本(ownCloud简体中文优化版)
通过安装Ubuntu16.04+LAMP+ownCloud9.1+SSL建立私有云,下载ownCloud android客户端最新源码,针对国际语言简体中文化,修改部分代码,并进行补充.优化,编译生成 ...
- Pomelo:网易开源基于 Node.js 的游戏服务端框架
Pomelo:网易开源基于 Node.js 的游戏服务端框架 https://github.com/NetEase/pomelo/wiki/Home-in-Chinese
- mysql in 排序
SELECT * FROM my_table WHERE id IN (30, 20, 80, 40) ORDER BY FIELD(id, 30, 20, 80, 40);
- android 虚线
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http: ...
- Python: 收集所有命名参数
有时候把Python函数调用的命名参数都收集到一个dict中可以更方便地做参数检查,或者直接由参数创建attribute等.更简单的理解就是def foo(*args, **kwargs): pass ...
- 第一篇HBuilder在这里!
本文作为一个引子,所有相关文章,都会在这里做一个索引,现在还空着.谢谢
- Web 技术人员需知的 Web 缓存知识(转)
最近的译文距今已有4年之久,原文有一定的更新.今天踩着前辈们的肩膀,再次把这篇文章翻译整理下.一来让自己对web缓存的理解更深刻些,二来让大家注意力稍稍转移下,不要整天HTML5, 面试题啊叨啊叨的~ ...
- Struts2的属性驱动与模型驱动的区别
1.Struts2的属性驱动. Struts2的属性驱动指的是在action中JSP页面的每一个form中的name都对应在action中有一个属性与之对应.看下面代码片段: <form act ...
- IE11 Enterprise Mode
对IE11引入的Enterprise Mode进行了一些总结,对查阅的一些参考资料直接引用了英文,需要注意的地方用中文进行了一些注解.供大家参考. 1. The purpose of introduc ...