加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用DisplayAttribute和自定义资源提供程序的ASP

发布时间:2020-12-15 23:17:26 所属栏目:asp.Net 来源:网络整理
导读:我使用自定义资源提供程序从数据库获取资源字符串.这可以在ASP.NET中正常工作,我可以将资源类型定义为字符串. MVC 3中的模型属性的元数据属性(如[范围],[显示],[必需])要求将资源作为参数的类型,其中ResourceType是.resx文件生成的代码隐藏类的类型. [Displa
我使用自定义资源提供程序从数据库获取资源字符串.这可以在ASP.NET中正常工作,我可以将资源类型定义为字符串. MVC 3中的模型属性的元数据属性(如[范围],[显示],[必需])要求将资源作为参数的类型,其中ResourceType是.resx文件生成的代码隐藏类的类型.
[Display(Name = "Phone",ResourceType = typeof(MyResources))]
    public string Phone { get; set; }

因为我没有.resx文件,这样的一个类不存在.如何使用模型属性与自定义资源提供程序?

我想要这样的东西:

[Display(Name = "Telefon",ResourceTypeName = "MyResources")]
    public string Phone { get; set; }

为此,System.ComponentModel的DisplayNameAttribute具有可覆盖的DisplayName属性,但是DisplayAttribute类被封装.对于验证属性,不存在对应的类.

解决方法

您可以扩展DisplayNameAttribute并覆盖DisplayName字符串属性.我有这样的东西
public class LocalizedDisplayName : DisplayNameAttribute
    {
        private string DisplayNameKey { get; set; }   
        private string ResourceSetName { get; set; }   

        public LocalizedDisplayName(string displayNameKey)
            : base(displayNameKey)
        {
            this.DisplayNameKey = displayNameKey;
        }


        public LocalizedDisplayName(string displayNameKey,string resourceSetName)
            : base(displayNameKey)
        {
            this.DisplayNameKey = displayNameKey;
            this.ResourceSetName = resourceSetName;
        }

        public override string DisplayName
        {
            get
            {
                if (string.IsNullOrEmpty(this.GlobalResourceSetName))
                {
                    return MyHelper.GetLocalLocalizedString(this.DisplayNameKey);
                }
                else
                {
                    return MyHelper.GetGlobalLocalizedString(this.DisplayNameKey,this.ResourceSetName);
                }
            }
        }
    }
}

对于MyHelper,方法可以是这样的:

public string GetLocalLocalizedString(string key){
    return _resourceSet.GetString(key);
}

显然,您将需要添加错误处理并设置resourceReader.更多信息here

这样,然后用新的属性来装饰你的模型,传递你要获取值的资源的关键字,像这样

[LocalizedDisplayName("Title")]

然后Html.LabelFor将自动显示本地化的文本.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读