我将自定义脚手架文件添加为CustomCreate.tt。在mvc添加视图对话框中,当我在对话框中选择我的自定义模板时出现错误。我可以调试我的文本模板文件吗?
答案 0 :(得分:2)
您可以尝试以下操作:
<#@ import namespace="System.Diagnostics" #>
)Trace.TraceError
您可以查看以下内容作为示例:
<#@ template language="C#" HostSpecific="True" #>
<#@ output extension="cs" #>
<#@ import namespace="System" #>
<#@ parameter type="System.String" name="ControllerName" #>
<#@ parameter type="System.String" name="ControllerRootName" #>
<#@ parameter type="System.String" name="Namespace" #>
<#@ parameter type="System.String" name="AreaName" #>
<#@ import namespace="System.Diagnostics" #>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
<# try{ #>
namespace <#= Namespace #>
{
public class <#= ControllerName #> : Controller
{
//
// GET: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/
public ActionResult Index()
{
return View();
}
//
// GET: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/Create
public ActionResult Create()
{
return View();
}
//
// POST: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: <#= (!String.IsNullOrEmpty(AreaName)) ? ("/" + AreaName) : String.Empty #>/<#= ControllerRootName #>/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
<# }
catch(Exception e)
{
Trace.TraceError(e.ToString());
throw;
}
#>
请注意,try-catch块包围了该类的所有模板代码。
调试T4模板的更好方法是添加断点,就像使用普通的CSharp和VB代码一样。要在T4模板上运行调试器,只需在解决方案资源管理器中右键单击它,然后从上下文菜单中选择调试T4模板。
以下文章还将帮助您解决常见的T4问题: Debugging a T4 Text Template
请注意,这仅适用于VS2012及以上版本。因此,我提到的第一种方法适用于使用旧版Visual Studio的开发人员。