【问题标题】:Access metadata (dataannotations) in my model from t4 scaffolding templates从 t4 脚手架模板访问我的模型中的元数据(数据注释)
【发布时间】:2012-04-13 07:24:09
【问题描述】:

如何从 T4 脚手架模板访问我的 asp.net mvc 模型类中的元数据(dataannotations 属性)?

我正在尝试读取 T4 模板中的 ScaffoldColumn 属性,因此它应该知道是否必须在索引视图中呈现某些列

谢谢

【问题讨论】:

    标签: asp.net-mvc t4 scaffolding asp.net-mvc-scaffolding t4scaffolding


    【解决方案1】:

    在 T4 模板中,您可以使用反射访问模型中的属性。如果您查看现有的 ASP.NET MVC 3 T4 模板,您将看到一个示例:

    C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 3\CodeTemplates\AddView\CSHTML\Details.tt
    

    涉及的基本代码如下所示:

    foreach (PropertyInfo prop in mvcHost.ViewDataType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) {
          if (Scaffold(prop)) {
              // ...
          }
    }
    
    bool Scaffold(PropertyInfo property) {
        foreach (object attribute in property.GetCustomAttributes(true)) {
            var scaffoldColumn = attribute as ScaffoldColumnAttribute;
            if (scaffoldColumn != null && !scaffoldColumn.Scaffold) {
                return false;
            }
        }
        return true;
    }
    

    【讨论】:

    猜你喜欢
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多