所以,这就是你的做法。
按照本教程了解如何创建自定义属性http://origin1tech.wordpress.com/2011/07/20/mvc-data-annotations-and-custom-attributes/
要在 T4 脚手架模板中读取此属性值,请首先按照此处所述添加模板文件 http://www.hanselman.com/blog/ModifyingTheDefaultCodeGenerationscaffoldingTemplatesInASPNETMVC.aspx
然后,例如,从 AddView 文件夹中打开 List.tt。此模板创建索引视图。
转到模板文件的末尾并找到类 ModelProperty 的定义。将您的属性值添加到它( public string MyAttributeValue { get; set; }
现在在 List.tt 中往下走一点,找到 bool Scaffold(PropertyInfo property) 方法。您将需要添加自己的属性属性阅读器。对于上述教程,此方法将是:
string OptionalAttributesValueReader(PropertyInfo property){
foreach (object attribute in property.GetCustomAttributes(true)) {
var attr = attribute as OptionalAttributes ;
if (attr != null) {
return attr.style;
}
}
return String.Empty;
}
然后在文件底部找到方法List GetEligibleProperties(Type type)。像这样添加你的阅读器:
...
IsForeignKey = IsForeignKey(prop),
IsReadOnly = prop.GetSetMethod() == null,
Scaffold = Scaffold(prop),
MyAttributeValue = OptionalAttributesValueReader(prop)
当您想使用和读取此属性时,您可以像在 List.tt 中使用 Scaffold 属性一样进行操作
List<ModelProperty> properties = GetModelProperties(mvcHost.ViewDataType);
foreach (ModelProperty property in properties) {
if (property.MyAttributeValue != String.Empty) {
//read the value
<#= property.MyAttributeValue #>
}
}
由于这些类是在我的项目中定义的,我不得不将我的项目 dll 和命名空间添加到 List.tt 的顶部:
<#@ assembly name="C:\myProjectPath\bin\myMVCproject.dll" #>
<#@ import namespace="myMVCproject.CustomAttributes" #>
如果你的模型发生变化,你需要在脚手架中找到这些新的变化,你需要重新构建你的项目。
希望任何寻找解决方案的人都会发现这很有用。请问有什么不清楚的地方。