一. 遇到的问题

文章开头部分想先说一下自己的困惑,在用AspNet MVC时,完成Action的编写,然后添加一个视图,这个时候弹出一个添加视图的选项窗口,如下:

  很熟悉吧,继续上面说的,我添加一个视图,强类型的、继承母版页的视图,点击确定,mvc会为我们添加一些自动生成的代码,感觉很方便。呵呵,刚开始的时候还真方便一些,但也仅仅只是方便一些而已。当遇到以下情景的时候,可能我们就不觉得了:

  程序中都要对N个实体类进行CRUD,就只说添加的功能,生成一个强类型的Create视图,但是这个自带的Create视图的布局可能并不能符合我们界面的要求,没关系啊,这个改改界面就ok了,这个是个不错的方法。但是有N个实体要进行CRUD的时候工作量就是time*N了,而且因为要求页面风格一致,我们几乎在做一样的工作,有必要吗?

  当然没必要了,应该把重复的工作交给程序去做,省点时间去……

  举个例子吧,自带的Create视图使用的是div进行排版的,而我们需要的是table来进行排版,这个改起来不难,但蛮麻烦的。为什么我就不能定制Create视图的模板,让它生成我想要的布局呢?这个可以有。

二. 解决问题

  经过多方搜罗,终于找到了AspNet MVC中用于生成这些视图的东东:T4(Text Template Transformation Toolkit)文本模板转换工具箱。在MVC项目中正是使用了T4来生成视图模板的,它藏在哪呢?是在你VS安装目录下:...\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web,在这个文件夹下面有MVC2、MVC3和MVC4的模板,创建什么项目就会用到对应的模板。这里只演示MVC3 生成Razor的,用2和4的同学就自己摸索了,都差不多的。在MVC3文件夹里面的CodeTemplates文件夹中包含了生成Controller和View两个文件夹。这里只说视图的,Controller里面的东西也可以去试试。在...\MVC 3\CodeTemplates\AddView\CSHTML,在这个文件夹下我们可以看到:

  这些正好是在创建强类型视图时系统自带的模板。好了,源头找到了,也应该进行修改了吧。不急,还有一点东西要了解,T4的基本编写语法:

T4基本语法

T4包括三个部分:

Directives(指令) 元素,用于控制模板如何被处理
Texts blocks(文本块) 用于直接复制到输出文件
Control blocks(控制块) 编程代码,用于控制变量显示文本

1)指令

  语法:

    <#@ DirectiveName [AttributeName = "AttributeValue"] … #>

常用的指令

    <#@ template [language="C#"] [hostspecific="true"] [debug="true"] [inherits="templateBaseClass"] [culture="code"] [complierOption="options"] #>

    <#@ parameter type="Full.TypeName" name="ParameterName" #>

    <#@ output extension=".fileNameExtension" [encoding="encoding"] #>

    <#@ assembly name="[assembly strong name| assembly file name]" #>

    <#@ import namespace="namespace" #>

    <#@ include file="filepath" #>

2)文本块

  只需要输入文本就可以了

3)控制块
<# #> 代码表达式
<#= #> 显示表达式值
<#+ #> 声明定义方法、变量
T4和MVC2中的界面编码非常类似,这就不用多说了吧。

  其实不仅仅有页面布局的问题,还有数据显示的问题,验证的问题等等,只要是界面上需要重复编写的东西都可以使用T4来减少工作量。

新建一个视图模板

  将CodeTemplates文件夹拷贝到项目程序的根目录下,覆盖默认视图模板。可以在MVC自带视图模板基础上进行修改,也可以自己新创建一个。建议做法是新建一个视图模板,是Text Template文件.tt后缀的,然后将要改动的系统视图代码复制过来,再进行修改。在此之前,选中所有CodeTemplates文件夹中的tt文件,右键属性,将Custome Tool项默认值清掉,原因还不清楚,知道的大虾指点下啊。(不去掉的话编译不通过,缺少了xxx程序集;也可以添加xxx程序集到项目中,不过没这个必要)

  如本文修改Create模板,新建一个newCreate.tt文件,与Create.tt文件在同一文件夹内,将Create.tt内容复制到newCreate.tt中,在此基础上进行修改。

  浏览一下newCreate.tt的代码

  包括设定输出文件格式,引入程序集和命名空间。这些和我们编写cs时差不多,不多讲了。

  最关键的是MvcTextTemplateHost这个类,这个类存储着视图信息,如视图名、视图类型(部分视图、强类型视图)、是否继承母版页等,具体的内容是有文章开篇的那一张图中设定的内容,即添加视图窗口的信息将会保存到MvcTextTemplateHost这个类实例去。好,那么这个类藏在哪呢?上网搜了一下,VS2008 sp1是在...\Microsoft Visual Studio 9.0\Common7\IDE\Microsoft.VisualStudio.Web.Extensions.dll这个程序集中定义的。不过我找了好久都没找到,可能是因为我用的是VS2010吧。还好最终还是找到了,是在...\Microsoft Visual Studio 10.0\Common7\IDE\Microsoft.VisualStudio.Web.Mvc.2.0.dll这个程序集中定义的,在Microsoft.VisualStudio.Web.Mvc命名空间内。具体的内容用Reflector反编译看下就知道了。

  啰嗦了好多东西,现在也该进入正题了。

修改视图生成界面

  将默认视图中div排版改成table排版,修改里面的back to list、Create等英文单词为中文。这个是最简单的修改了,只需修改tt文件的文本块内容就可以了。直接上效果图了:

  添加视图,这时我们自己新定义的模板已经在列表框中了:

  

  两个模板的效果,左边是由newCreate模板生成的,右边是由Create模板生成

  

  这个只是做了一下简单的页面修改,想怎么改就看具体要求了。

与Jquery联用,自动添加时间插件

  如果仅仅只是修改一下界面,那真的没必要这么大费周章的,我们还可以再进一步改进。在出生日期这一编辑框中,我们往往都会使用一个jquery时间插件来美化。那我们可不可以让newCreate.tt文本模板在检测到DateTime类型时自动添加js代码,答案是可以的。

  在开始之前肯定是要先下载需要的js文件,布置到项目中。这里就只贴出关键部分的代码和效果图:

  

View Code

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>    <script src="@Url.Content( "~/Content/jquery-ui/jquery-ui-1.8.12.custom.min.js")" type="text/javascript"></script>    <script src="@Url.Content( "~/Content/jquery-ui/jquery-ui-i18n.min.js")" type="text/javascript"></script>    <script src="@Url.Content( "~/Content/jquery-ui-timepicker-addon.js")" type="text/javascript"></script>    <link href="@Url.Content( "~/Content/jquery-ui/redmond/jquery-ui-1.8.5.custom.css")" rel="stylesheet" type="text/css" />    <script type="text/javascript">        $(document).ready(function () {// 自动绑定时间插件            <#        foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {if (property.UnderlyingType == typeof(DateTime)) {        #>        $('#<#= property.Name #>').datetimepicker({            currentText: '当前时间',            closeText: '完成',            timeText: '时间',            hourText: '小时',            minuteText: '分钟',            dateFormat: 'yy年mm月dd日',        });        <#            }        }        #>        });    </script>

  

  这样只要程序中有用到时间的地方就会自动生成js代码然后就方便很多了。当然可以写个MVC的html扩展方法来实现,方便的程度差不多吧。

数据验证

  还可以再改进么?必然可以,只要你想得到。数据验证,这个在添加编辑数据的地方都会用到。这回不说能够全自动吧,起码也是半自动。其实在MVC中已经有通过后台编写Metadata来进行数据验证了,不过那个是在后台。这回要做的是在前端页面进行半自动添加js验证代码。要想做得方便的话就得自己编写一些js代码,这个肯定要的,方便的前提是先需要复杂一段时间(不过也没多复杂)。

  在做验证的时候,我们无非要验证不可空、验证数字、手机号码、邮件地址等这些东西。还有一点是js代码是通过文本模板生成的,这就要求我们需要创建一个通用的验证函数。这个函数怎么设计呢?想想,每一个验证都会对应一个form表单、需要验证的格式、验证不通过时的提示信息。也就是说这个js函数有三个参数:

  1 被验证的表单的id:这个可以在文本模板中获得

  2 验证的格式:这个编写一个js的枚举类型吧,把要用到的所有格式的正则表达式写好。

  3 提示信息:这个总不能也要自动生成吧

  说了思路我就直接贴代码和效果图了,想去了解的可以下载程序来看一下。

  看一下这个自动生成的js代码:

  

  第一个formValidatorRegex.js文件存储的就是各种格式的正则表达式。

  第二个formValidatorUI.js文件是checkValue这个验证函数的定义。

  自动生成之后就可以做一些小的修改来达到我们需要的验证功能了,两个地方要修改的,第一个就是设置验证格式,第二个是填写提示信息。

  现在把newCreate.tt的全部代码献上:

  

View Code

<#@ template language="C#" HostSpecific="True" #><#@ output extension=".cshtml" #><#@ assembly name="System.ComponentModel.DataAnnotations" #><#@ assembly name="System.Core" #><#@ assembly name="System.Data.Entity" #><#@ assembly name="System.Data.Linq" #><#@ import namespace="System" #><#@ import namespace="System.Collections.Generic" #><#@ import namespace="System.ComponentModel.DataAnnotations" #><#@ import namespace="System.Data.Linq.Mapping" #><#@ import namespace="System.Data.Objects.DataClasses" #><#@ import namespace="System.Linq" #><#@ import namespace="System.Reflection" #><#MvcTextTemplateHost mvcHost = (MvcTextTemplateHost)(Host);  // 关键类,其实例是通过Add View窗口所做的设定获取的#>@model <#= mvcHost.ViewDataTypeName #>    <#// The following chained if-statement outputs the file header code and markup for a partial view, a content page, or a regular view.if(mvcHost.IsPartialView) {    // 部分视图#>

<#} else if(mvcHost.IsContentPage) {    // 内容页#>

@{    ViewBag.Title = "<#= mvcHost.ViewName#>";    @*ViewName视图名,第一张图中的View name 中的值*@<#if (!String.IsNullOrEmpty(mvcHost.MasterPageFile)) {    // 母版页#>    Layout = "<#= mvcHost.MasterPageFile#>";    @*MasterPageFile母版页路径*@<#}#>}

<h2><#= mvcHost.ViewName#></h2>

<#} else {#>

@{    Layout = null;}

<!DOCTYPE html>

<html><head>    <title><#= mvcHost.ViewName #></title></head><body><#    PushIndent("");}#><#if (mvcHost.ReferenceScriptLibraries) {    // ReferenceScriptLibraries是否勾取了引入javascript脚本库#><#if (!mvcHost.IsContentPage) {#><script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script><#    }#><script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script><script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<#}#>@using (Html.BeginForm()) {    @Html.ValidationSummary(true)    <fieldset>        <legend><#= mvcHost.ViewDataType.Name #></legend>        <table class="cls"><#foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {if (!property.IsPrimaryKey && !property.IsReadOnly) {#>        <tr>            <td>                @Html.LabelFor(model => model.<#= property.Name #>)            </td>            <td>                @Html.EditorFor(model => model.<#= property.Name #>)                @Html.ValidationMessageFor(model => model.<#= property.Name #>)            </td>        </tr><#    }}#>        <tr>            <td></td>            <td><input type="submit" id="submit1" value="创建" /></td>        </tr>        </table>    </fieldset>}

<div>    @Html.ActionLink("返回列表", "Index")</div><div id="alertDialog" title="消息提示"></div>

    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>    <script src="@Url.Content( "~/Content/jquery-ui/jquery-ui-1.8.12.custom.min.js")" type="text/javascript"></script>    <script src="@Url.Content( "~/Content/jquery-ui/jquery-ui-i18n.min.js")" type="text/javascript"></script>    <script src="@Url.Content( "~/Content/jquery-ui-timepicker-addon.js")" type="text/javascript"></script>    <link href="@Url.Content( "~/Content/jquery-ui/redmond/jquery-ui-1.8.5.custom.css")" rel="stylesheet" type="text/css" />    <script src="@Url.Content("~/Content/formValidatorRegex.js")" type="text/javascript"></script>    <script src="@Url.Content("~/Content/formValidatorUI.js")" type="text/javascript"></script>

    <script type="text/javascript">        $(document).ready(function () {// 添加验证代码        $("#submit1").click(function () {if (1==2  //初始化,验证默认不通过(验证时将其删除)                <#foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {                #>                    && checkValue($("#<#= property.Name #>").val(), "", "")                <#                }                #>                ) {  //checkValue($("#").val(), regexEnum, "") //第1个参数是需要验证的值//第2个参数为正则表达式//第3个参数是验证不通过的提示信息                    return true;                }return false;            });

// 自动绑定时间插件            <#foreach (ModelProperty property in GetModelProperties(mvcHost.ViewDataType)) {if (property.UnderlyingType == typeof(DateTime)) {        #>        $('#<#= property.Name #>').datetimepicker({            currentText: '当前时间',            closeText: '完成',            timeText: '时间',            hourText: '小时',            minuteText: '分钟',            dateFormat: 'yy年mm月dd日',        });        <#            }        }        #>        });    </script>

<#// The following code closes the asp:Content tag used in the case of a master page and the body and html tags in the case of a regular view page#><#if(!mvcHost.IsPartialView && !mvcHost.IsContentPage) {    ClearIndent();#></body></html><#}#>

<#+// Describes the information about a property on the modelclass ModelProperty {public string Name { get; set; }public string ValueExpression { get; set; }public Type UnderlyingType { get; set; }public bool IsPrimaryKey { get; set; }public bool IsReadOnly { get; set; }}

// Change this list to include any non-primitive types you think should be eligible for display/editstatic Type[] bindableNonPrimitiveTypes = new[] {typeof(string),typeof(decimal),typeof(Guid),typeof(DateTime),typeof(DateTimeOffset),typeof(TimeSpan),};

// Call this to get the list of properties in the model. Change this to modify or add your// own default formatting for display values.List<ModelProperty> GetModelProperties(Type type) {    List<ModelProperty> results = GetEligibleProperties(type);

foreach (ModelProperty prop in results) {if (prop.UnderlyingType == typeof(double) || prop.UnderlyingType == typeof(decimal)) {            prop.ValueExpression = "String.Format(\"{0:F}\", " + prop.ValueExpression + ")";        }else if (prop.UnderlyingType == typeof(DateTime)) {            prop.ValueExpression = "String.Format(\"{0:g}\", " + prop.ValueExpression + ")";        }    }

return results;}

// Call this to determine if the property represents a primary key. Change the// code to change the definition of primary key.bool IsPrimaryKey(PropertyInfo property) {if (string.Equals(property.Name, "id", StringComparison.OrdinalIgnoreCase)) {  // EF Code First convention        return true;    }

if (string.Equals(property.Name, property.DeclaringType.Name + "id", StringComparison.OrdinalIgnoreCase)) {  // EF Code First convention        return true;    }

foreach (object attribute in property.GetCustomAttributes(true)) {if (attribute is KeyAttribute) {  // WCF RIA Services and EF Code First explicit            return true;        }

var edmScalar = attribute as EdmScalarPropertyAttribute;if (edmScalar != null && edmScalar.EntityKeyProperty) {  // EF traditional            return true;        }

var column = attribute as ColumnAttribute;if (column != null && column.IsPrimaryKey) {  // LINQ to SQL            return true;        }    }

return false;}

// This will return the primary key property name, if and only if there is exactly// one primary key. Returns null if there is no PK, or the PK is composite.string GetPrimaryKeyName(Type type) {    IEnumerable<string> pkNames = GetPrimaryKeyNames(type);return pkNames.Count() == 1 ? pkNames.First() : null;}

// This will return all the primary key names. Will return an empty list if there are none.IEnumerable<string> GetPrimaryKeyNames(Type type) {return GetEligibleProperties(type).Where(mp => mp.IsPrimaryKey).Select(mp => mp.Name);}

// HelperList<ModelProperty> GetEligibleProperties(Type type) {    List<ModelProperty> results = new List<ModelProperty>();

foreach (PropertyInfo prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) {    // 遍历所有公共实例属性        Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;    // 去掉可空之后的类型// GetGetMethod()获取公共get访问器(就是属性定义中的get方法)、GetIndexParameters()获取索引器// 这个判断条件就是属性必须有get方法,且不能为索引器类型,再一个返回类型必须是基元类型或者[String、Guid、DateTime、TimeSpan、decimal、TimeSpan、DateTimeOffset]这些类型之一        if (prop.GetGetMethod() != null && prop.GetIndexParameters().Length == 0 && IsBindableType(underlyingType)) {            results.Add(new ModelProperty {    // 添加到ModelProperty                Name = prop.Name,                ValueExpression = "Model." + prop.Name,                UnderlyingType = underlyingType,                IsPrimaryKey = IsPrimaryKey(prop),                IsReadOnly = prop.GetSetMethod() == null            });        }    }

return results;}

// Helperbool IsBindableType(Type type) {return type.IsPrimitive || bindableNonPrimitiveTypes.Contains(type);}

#>

  好了,写得差不多了。其实还好很多可以改进的地方,感兴趣的同学可以再去修改一下默认的controller模板,然后再结合自己自定的视图模板,完成一个实体的简单增删改查应该用10分钟就可以搞定了,只是简单的,不要想太多了。

  程序下载:MvcT4Project

  ps:在2011年11月11日巨型光棍节这天送上自己的处男作,希望自己和园子里面所有的兄弟早日脱离光棍大军,祝大家节日快乐!

  ps again:文章有说得不清楚或不详细的地方还望海涵。

  

转载于:https://www.cnblogs.com/hbq-fczzw/archive/2011/11/11/2191614.html

AspNet MVC与T4,我定制的视图模板相关推荐

  1. ASP .NET Core Web MVC系列教程三:添加视图

    系列文章目录:ASP .NET Core Web MVC系列教程:使用ASP .NET Core创建MVC Web应用程序 上一个教程:ASP .NET Core Web MVC系列教程二:添加控制器 ...

  2. ASP.NET MVC 5 学习教程:修改视图和布局页

    ASP.NET MVC 5 学习教程:修改视图和布局页 原文 ASP.NET MVC 5 学习教程:修改视图和布局页 起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图 ...

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

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

  4. ASPNET MVC Error 403.14

    今天创建了一个新的ASPNET MVC 项目部署到本地, 生成成功后在浏览器中输入URL却发现报这个错 解决办法: 因为我的站点是4.5的,但是我没有设置Application Pool所以当前还是默 ...

  5. ASPNET MVC项目设置起始页问题修复

    刚开始研究ASPNET MVC,使用的MVC2.0框架. 不小心将"Views"文件夹里面点了设置起始页,运行一直出错,不知道在哪里取消掉起始页的设置. 由于使用了SVN,发现改过 ...

  6. SpringBoot2.0系列(03)---SpringBoot之使用freemark视图模板

    前言 freemarker介绍: FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户 ...

  7. SpringBoot2.0系列(2)---SpringBoot之使用Thymeleaf视图模板

    前言 Thymeleaf 是Java服务端的模板引擎,与传统的JSP不同,前者可以使用浏览器直接打开,因为可以忽略掉拓展属性,相当于打开原生页面,给前端人员也带来一定的便利.如果你已经厌倦了JSP+J ...

  8. go html template 数据怎么加减乘除_Go 视图模板篇(五):模板布局和继承

    模板布局与继承 在 Go 模板中,可以结合 define 指令和 template 指令实现模板布局功能. 首先编写一段服务端示例代码: package main import ( "htm ...

  9. Express4.X版本修改默认模板jade为ejs并且试用html为视图模板后缀名

    通过npm安装Express4.x版本之后发现默认的视图模板是jade的,如果想使用ejs模板的话先通过npm安装ejs npm install ejs 然后打开app.js文件,把里面的 app.s ...

最新文章

  1. 《计算机网络》常考概念、英文缩写、公式大全
  2. Mocha NTA基于单采集器实现的多种流协议分析
  3. html5复选框样式,11种炫酷CSS3复选框checkbox样式美化效果
  4. linux resin 自动启动不了,Resin 安装-配置-自启动-Linux
  5. const和define 区别
  6. 开启Windows或者Mac OSX 本地服务器 (非安装第三方服务器软件)
  7. Mysql大小写敏感问题
  8. “勒索文件”或可部分恢复
  9. 纪中游记 - Day 3
  10. 全面解读设备状态监测
  11. JAVA SE — Day 18
  12. 钱符号怎么打出来(如何在文档中输入人民币符号?)
  13. xcode更新一直失败的解决办法
  14. MOV PC, LR解析
  15. Flowerpot(单调队列)
  16. Linux虚拟机(lvm)报Unmount and run xfs_repair
  17. Conflux迎来重大升级,引入EVM兼容空间及PoS链
  18. 练习赛 | Datawhale和Kesci联合发起的比赛实践
  19. k8s容器优雅退出一则研究
  20. 【数据挖掘实验】聚类分析方法

热门文章

  1. python【力扣LeetCode算法题库】70-爬楼梯
  2. 文件操作03——图片文件合成器
  3. 计算机仿真实训操作开车步骤,仿真实训系统解决方案
  4. oracle clob raw 转换,ORA-22835 缓冲区对于 CLOB 到 CHAR 转换或 BLOB 到 RAW 转换而言太小...
  5. oracle日期导出mysql_oracle的数据导入到mysql中,遇到一个时间转换问题
  6. php修改http header,php header函数的常用http头设置
  7. linux 新建用户_使用Xshell和Xftp连接管理Linux服务器
  8. android 轮播 getWith,NavigationTermSet.GetWithNewView 方法
  9. 长春工业大学计算机专科吧,长春工业大学是几本 学生评价怎么样好不好(10条)...
  10. java logout session_在jsp里做“退出登录”, session.setAttribute(id,null)居然出错。高手救命啊!...