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应用程序创建自定义视图引擎的更多相关文章

  1. [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:为ASP.NET MVC应用程序创建更复杂的数据模型

    这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第六篇:为ASP.NET MVC应用程序 ...

  2. 为ASP.NET MVC应用程序创建更复杂的数据模型

    为ASP.NET MVC应用程序创建更复杂的数据模型 2014-05-07 18:27 by Bce, 282 阅读, 1 评论, 收藏, 编辑 这是微软官方教程Getting Started wit ...

  3. Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型

    原文 Contoso 大学 - 1 - 为 ASP.NET MVC 应用程序创建 EF 数据模型 原文地址:Creating an Entity Framework Data Model for an ...

  4. ASP.NET MVC自定义视图引擎ViewEngine 创建Model的专属视图

    MVC内置的视图引擎有WebForm view engine和Razor view engine,当然也可以自定义视图引擎ViewEngine. 本文想针对某个Model,自定义该Model的专属视图 ...

  5. Asp.net MVC 移除不用的视图引擎

    Asp.net MVC 默认提供两个视图引擎,分别为: WebFormViewEngine 和 RazorViewEngine.MVC在查找视图时,会按照指定的顺序进行查找.当我们的MVC程序未找到相 ...

  6. ASP.NET MVC扩展自定义视图引擎支持多模板&动态换肤skins机制

    ASP.NET mvc的razor视图引擎是一个非常好的.NET MVC框架内置的视图引擎.一般情况我们使用.NET MVC框架为我们提供的这个Razor视图引擎就足够了.但是有时我们想在我们的项目支 ...

  7. ASP.NET MVC 扩展自定义视图引擎支持多模板&动态换肤skins机制

    ASP.NET  mvc的razor视图引擎是一个非常好的.NET  MVC 框架内置的视图引擎.一般情况我们使用.NET MVC框架为我们提供的这个Razor视图引擎就足够了.但是有时我们想在我们的 ...

  8. 创建自定义视图在Android矩阵效果画布教程

    介绍 下面是一个快速教程,教你如何在Android中创建自定义视图.自定义视图创建一个矩阵雨效果. 本教程发布在http://www.androidlearner.com/. 背景 下面是关于如何工作 ...

  9. 自定义视图引擎,实现MVC主题快速切换

    一个网站的主题包括布局,色调,内容展示等,每种主题在某些方面应该或多或少不一样的,否则就不能称之为不同的主题了.每一个网站至少都有一个主题,我这里称之为默认主题,也就是我们平常开发设计网站时的一个固定 ...

随机推荐

  1. 无锁编程以及CAS

    无锁编程 / lock-free / 非阻塞同步 无锁编程,即不使用锁的情况下实现多线程之间的变量同步,也就是在没有线程被阻塞的情况下实现变量的同步,所以也叫非阻塞同步(Non-blocking Sy ...

  2. 向Spotify学习如何设计产品(转)

    导语:Spotify是瑞典的精益创业项目,同时保持着很棒的产品交付记录.一般在产品上线之后,开发者才知道人们喜不喜欢它.Spotify如何解决这个问题? 本文转自 kent.zhu's Blog,原文 ...

  3. 让Asp.Net WebAPI支持OData查询,排序,过滤。

    让Asp.Net WebAPI支持OData后,就能支持在url中直接输入排序,过滤条件了. 一.创建Asp.Net WebAPI项目: 二.使用NuGet安装Asp.Net WebAPI 2.2和O ...

  4. Scala 深入浅出实战经典 第58讲:Scala中Abstract Types实战详解

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载: 百度云盘:http://pan.baidu.com/s/1c0noOt ...

  5. PHP 数组排序方法总结

    sort:本函数为 array 中的单元赋予新的键名.这将删除原有的键名而不仅是重新排序. rsort:本函数对数组进行逆向排序(最高到最低). 删除原有的键名而不仅是重新排序. asort:对数组进 ...

  6. Android开发(二十六)——Application

    application package com.lgaoxiao.application; import java.util.LinkedList; import java.util.List; im ...

  7. Python: 收集所有命名参数

    有时候把Python函数调用的命名参数都收集到一个dict中可以更方便地做参数检查,或者直接由参数创建attribute等.更简单的理解就是def foo(*args, **kwargs): pass ...

  8. ubuntu-15.04-server-i386.iso 安装 Oracle 11gR2 数据库

    特点: 需要重新安装老版本的 libaio1_0.3.109-2ubuntu?_i386.deb.默认的libaio库有问题,和其默认libaio的编译方式有关! 默认的gcc 4.9 需要使用 -W ...

  9. web app变革之rem(手机屏幕实现全适配)

    以往web移动适配,常规写法是:media only screen @media only screen and (min-device-width: 320px){ //针对iPhone 3 } @ ...

  10. Cubieboard2裸机开发之(四)定时器操作

    前言 在Cubieboard2裸机开发之(三)里用到了一个延时函数delay,它的延时时间是不精确的,因此为了能够精确延时,就需要定时器的配合.定时器可以精确延时的一个重要原因是它的计时时钟(或者说频 ...