簡體   English   中英

MVC3自定義模板t4和DataAnnotations

[英]MVC3 custom template t4 and DataAnnotations

這是我的DataAnnotations模型

[DisplayName("Title1"),Display(Name="Title2")]
public class MyClass
{
  [Display(Name = "My Class Name")]
  public string class_name { get; set; }
}

我想知道如何在我的T4模板Index.cs.t4中訪問類MyClass的這些DataAnnotations(即DisplayName屬性)。

<# } #>
@{
  ViewBag.Title = "<#= viewDataType.Name   #>";
  <# if (!String.IsNullOrEmpty(Model.Layout)) { #>
  Layout = "<#= Model.Layout #>";
<# } #>
}

而不是放置viewDataType.Name我想擁有類MyClass的DisplayName屬性的值

謝謝

MVC腳手架模板使用Visual Studio對象模型,這與標准ASP.NET MVC模板的工作方式不同。 Model.ViewDataType是Visual Studio EnvDTE.CodeType類,而不是Type類。 EnvDTE.CodeType具有可以用來獲取顯示名稱的attributes屬性。

這是一些示例代碼,可用於從CodeType獲取顯示名稱。 您可以將此代碼放在自定義T4模板(Index.cs.t4)的末尾。

<#+
string GetDisplayName(EnvDTE.CodeType type) {
    if (type != null) {
        foreach (var attribute in type.Attributes.OfType<EnvDTE.CodeAttribute>()) {
            if (attribute.Name == "DisplayName") {
                return attribute.Value;
            }
        }
    }
    return "";
}
#>

然后,在您的自定義T4模板中,可以將ViewDataType.Name替換為對GetDisplayName()的調用。 我還刪除了“ <#= viewDataType.Name#> ”周圍的引號,因為T4模板圍繞從<#= GetDisplayName(viewDataType)#>返回的結果生成引號。

<# var viewDataType = (EnvDTE.CodeType) Model.ViewDataType; #>
<# if(viewDataType != null) { #>
@model IEnumerable<<#= viewDataType.FullName #>>
<# } #>
@{
    ViewBag.Title = <#= GetDisplayName(viewDataType) #>;
<# if (!String.IsNullOrEmpty(Model.Layout)) { #>
    Layout = "<#= Model.Layout #>";
<# } #>
}

如果然后刪除Index.cshtml視圖並使用腳手架再次重新創建,則應該在ViewBag.Title中設置顯示名稱。

@{
    ViewBag.Title = "Title1";
}

更新

通過為您提供恰好能回答您問題的帖子的參考,我完全刪除了我的答案和答案(並且答案都適用於兩種方式)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM