asp.net-mvct4scaffoldingasp.net-mvc-scaffoldingt4scaffolding

Access metadata (dataannotations) in my model from t4 scaffolding templates


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


Solution

  • 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;
    }