简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM