1

How can I access metadata (dataannotations attributes) in my asp.net mvc model class from a T4 scaffolding template?

I'm trying to read the ScaffoldColumn attribute in the T4 template so it should know if must render some columns in the index view

Thanks

Rodrigo Juarez
  • 1,745
  • 1
  • 23
  • 38

1 Answers1

1

From within a T4 template you can access attributes from your model using reflection. If you take a look at the existing ASP.NET MVC 3 T4 templates you will see an example:

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

The basic code involved is shown below:

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;
}
Matt Ward
  • 47,057
  • 5
  • 93
  • 94
  • I'm trying to use MVC Scaffolding (http://mvcscaffolding.codeplex.com/) and I use EnvDTE to read the ScaffoldColumn attributes instead reflection, here is an example (https://gist.github.com/1272922/cc263aac02c1916ade9720c13c1da015b4f2e9e6) – Rodrigo Juarez Apr 05 '12 at 13:33