利用VS2010,给自己的ASP.NET MVC添加自己的控制器模板
2011-04-08 16:55 音乐让我说 阅读(1376) 评论(0) 收藏 举报利用VS2010,给自己的ASP.NET MVC添加自己的控制器模板,也就是新建一个Controller的时候,默认的代码。
步骤如下:
1. 新建一个MVC项目,在根目录下依次新建CodeTemplates>AddController文件夹。
2. 在AddController文件夹下新建Controller.tt文件,截图如下:

3. 编写你的模板,我编写的如下:
<#@ template language="C#" HostSpecific="True" #>
<#@ import namespace="" #>
<#
var mvcHost = (MvcTextTemplateHost)(Host);
// You can use Reflector to see the available MvcTextTemplateHost properties, it's in this assembly:
// "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\Microsoft.VisualStudio.Web.Mvc.3.0.dll"
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace <#= mvcHost.Namespace #>
{
public partial class <#= mvcHost.ControllerRootName #>Controller : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IndexModel model)
{
if (!ModelState.IsValid)
{
return View();
}
return null;
}
}
public partial class <#= mvcHost.ControllerRootName #>Controller
{
public class IndexModel
{
// public string Property1 { get; set; }
}
}
}
4. 右键Controller.tt属性,清空“自定义工具”对应的值,刚开始我没有清空,编译时就报错,后来参考http://stackoverflow.com/questions/1045066/mvctexttemplatehost-not-found 后才知道要清空。截图如下:

5. 编译生成,OK!

以后就可以添加自己的Controller模板了!
谢谢浏览!
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
浙公网安备 33010602011771号