【问题标题】:DisplayFormat data annotation using resource string使用资源字符串的 DisplayFormat 数据注释
【发布时间】:2012-02-22 15:46:26
【问题描述】:

我想使用 DisplayFormat 数据注释来格式化我的模型数据,但我想使用存储在资源文件中的格式字符串。我已经能够将资源类型和名称传递给某些数据注释,例如在指定错误消息时。如何告诉 DisplayFormat 从我的资源文件之一中获取格式字符串?

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    标准的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}

    【讨论】:

    • 我怀疑我必须自己做这件事。谢谢
    • MyMessages 应该是MyResources 对吧?如果它也作为类型传递就完美了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2011-02-04
    • 2016-04-17
    • 2011-05-08
    • 2019-05-25
    相关资源
    最近更新 更多