ASP.NETMVCアプリケーションでDataAnnotationsを使用したいと思います。リソースクラスを強く型付けし、ビューモデルで定義したいと思います。
[DisplayName(CTRes.UserName)]
string Username;
CTRes
私のリソースであり、自動生成されたクラスです。上記の定義は許可されていません。他に解決策はありますか?
ASP.NETMVCアプリケーションでDataAnnotationsを使用したいと思います。リソースクラスを強く型付けし、ビューモデルで定義したいと思います。
[DisplayName(CTRes.UserName)]
string Username;
CTRes
私のリソースであり、自動生成されたクラスです。上記の定義は許可されていません。他に解決策はありますか?
.NET 4.0で追加されたDisplayAttributeがあり、リソース文字列を指定できます。
[Display(Name = "UsernameField")]
string Username;
まだ.NET4.0を使用できない場合は、独自の属性を作成できます。
public class DisplayAttribute : DisplayNameAttribute
{
public DisplayAttribute(Type resourceManagerProvider, string resourceKey)
: base(LookupResource(resourceManagerProvider, resourceKey))
{
}
private static string LookupResource(Type resourceManagerProvider, string resourceKey)
{
var properties = resourceManagerProvider.GetProperties(
BindingFlags.Static | BindingFlags.NonPublic);
foreach (var staticProperty in properties)
{
if (staticProperty.PropertyType == typeof(ResourceManager))
{
var resourceManager = (ResourceManager)staticProperty
.GetValue(null, null);
return resourceManager.GetString(resourceKey);
}
}
return resourceKey;
}
}
あなたはこのように使うことができます:
[Display(typeof(Resources.Resource), "UsernameField"),
string Username { get; set; }
これは、ScottGuの投稿で述べられているように、MVC3で正常に機能するようになり、ローカライズされたリソースファイルで組み込みのDisplayAttributeを使用できるようになります。
属性はこれを行うことができません
リソースファイルのC#属性テキストを参照してください。
Resource.ResourceNameは文字列プロパティになり、属性パラメーターは定数、列挙型、typeofsのみになります