我想使用 DisplayFormat 数据注释来格式化模型数据,但我想使用资源文件中存储的格式字符串。我已经能够将资源类型和名称传递给某些数据注释,例如指定错误消息时。如何告诉 DisplayFormat 从我的资源文件之一获取格式字符串?
标准DisplayFormat
属性不允许你这样做。您可以编写自定义属性来实现此功能:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class LocalizedDisplayFormatAttribute : Attribute, IMetadataAware
{
public string DataFormatStringResourceName { get; set; }
public bool ApplyFormatInEditMode { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (!string.IsNullOrEmpty(DataFormatStringResourceName))
{
if (ApplyFormatInEditMode)
{
metadata.EditFormatString = MyMessages.ResourceManager.GetString(DataFormatStringResourceName);
}
metadata.DisplayFormatString = MyMessages.ResourceManager.GetString(DataFormatStringResourceName);
}
}
}
进而:
public class MyViewModel
{
[LocalizedDisplayFormat(DataFormatStringResourceName = "DobFormat", ApplyFormatInEditMode = true)]
public DateTime Dob { get; set; }
}
和里面MyResources.resx
你可以有一个DobFormat
字符串值:{0:dd-MM-yyyy}
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)