2010-03-25 17 views
3

可能重複:
DisplayName attribute from Resources?如何在ASP.NET MVC2中使用和/或本地化DisplayAttribute?

我試圖找出如何讓DisplayAttribute在我的MVC 2視圖模型與Html.LabelFor()輔助工作。

無論

public class TestModel 
{ 
    [Display(ResourceType = typeof(Localization.Labels))] 
    public string Text { get; set; } 
} 

也不

public class TestModel 
{ 
    [Display(Name = "test")] 
    public string Text { get; set; } 
} 

似乎工作。本地化所需的屬性按預期工作:

[Required(ErrorMessageResourceName = "Test", ErrorMessageResourceType = typeof(Localization.Labels))] 

我正在使用VS2010 RC。有沒有人得到這個運行?

回答

12

[Display]屬性是.NET 4特有的屬性。由於MVC 2是針對.NET 3.5編譯的,因此運行時無法識別此屬性。

有關更多信息和解決方法,請參閱http://aspnet.codeplex.com/WorkItem/View.aspx?WorkItemId=5515

編輯:

嗯,工作項目不是那麼大了。也可以包含它內聯。 :)

的[顯示]屬性是 DataAnnotations V4新的,所以MVC 2不能使用 它,因爲我們對 DataAnnotations V3.5編譯。直到使用 [DisplayName],直到MVC 3, ,我們將根據 編輯DataAnnotations v4。

您有幾個解決方法。當.NET 4的RTM,我們將提供一個.NET 4特異性期貨二進制,那 期貨二進制將具有元數據 提供商能夠理解[顯示] 等DataAnnotations V4-特定 屬性。另外,如果您需要 的解決方案的時候了,子類 [顯示名稱]屬性,製作一部適當實例化的 私人DisplayNameAttribute場 ,並 重寫虛 DisplayNameAttribute.DisplayName 屬性,以便它委託給 _theWrappedDisplayNameAttribute.GetName ()。

public class MultiCulturalDisplayName : DisplayNameAttribute { 
    private DisplayAttribute display; 

    public MultiCulturalDisplayName(Type resourceType, string resourceName) { 
    this.display = new DisplayAttribute { ResourceType = resourceType, Name = resourceName }; 
    } 

    public override string DisplayName { 
    get { return display.GetName(); } 
    } 
} 
+0

是的,我現在使用了一個非常類似的解決方案。謝謝。 – 2010-03-26 11:41:11

1

李維斯幾乎回答了你的問題,併爲這裏的記錄是3.5

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 
public class DisplayNameLocalizedAttribute : DisplayNameAttribute 
{ 
    public DisplayNameLocalizedAttribute(Type resourceType, string resourceKey) 
     : base(LookupResource(resourceType, resourceKey)) { } 

    internal static string LookupResource(Type resourceType, string resourceKey) 
    { 
     PropertyInfo property = resourceType.GetProperties().FirstOrDefault(p => p.PropertyType == typeof(System.Resources.ResourceManager)); 
     if (property != null) 
     { 
      return ((ResourceManager)property.GetValue(null, null)).GetString(resourceKey); 
     } 
     return resourceKey; 
    } 
} 
3

工作版本如果你下載ASP.NET MVC 2 Futures組裝,然後你可以使用DisplayAttribute。您只需要將DataAnnotations4ModelMetadataProvider.RegisterProvider();添加到您的Global.asax。cs

相關問題