利用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模板了!
谢谢浏览!