gpt4 book ai didi

asp.net-mvc - ASP.NET 自定义本地化

转载 作者:行者123 更新时间:2023-12-02 05:07:05 24 4
gpt4 key购买 nike

我已经做了相当多的研究,但我不确定我应该如何着手进行研究。

通常的本地化只会在语言发生变化时发生变化,因此法语的 Hello 将是 Bonjour,但我的应用程序需要为某些用户提供特殊关键字,因此 UserX 可能会说“Hello”需要是“Allo”。

我想使用 IdentityName_resourceKey 获取资源 key ,如果存在此 key ,则使用它,否则退回到 resourceKey

我想我需要一个自定义 ResourceProvider,但我的实现是一个简单的 if 语句,所以我不想编写一个完整的资源提供程序。

我写了一个 DisplayName 属性的扩展,它工作正常,但这不是很好,因为我将需要一个用于每个数据注释属性,如果我直接在页面或 Controller 中使用资源,这将不起作用......

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
private readonly PropertyInfo _propertyInfo;

public LocalizedDisplayNameAttribute(string resourceKey, Type resourceType) : base(resourceKey)
{
var clientName = CustomMembership.Instance.CurrentUser.Client.Name;

_propertyInfo = resourceType.GetProperty(clientName + "_" + base.DisplayName, BindingFlags.Static | BindingFlags.Public)
?? resourceType.GetProperty(base.DisplayName, BindingFlags.Static | BindingFlags.Public);
}

public override string DisplayName
{
get
{
if (_propertyInfo == null)
{
return base.DisplayName;
}

return (string) _propertyInfo.GetValue(_propertyInfo.DeclaringType, null);
}
}
}

我正在寻找用最少的代码实现它的最佳方法..

谢谢!

最佳答案

有更好的方法,Data Annotations 就是您的答案!

这只是一个示例,您需要更深入地了解 System.Globalization.CultureInfo 和数据注释 (System.ComponentModel.DataAnnotations)

您可以像这样定义您的模型类(假设我们有一个名为 CustomResourceValues 的资源文件,其值为“strHello”)

public class SomeObject(){

<Display(Name:="strHello", ResourceType:=GetType(My.Resources.CustomResourceValues))>
public string HelloMessage{ get; set; }

}

因此,在我们看来,工作必须由 htmlhelper 完成(假设像渲染引擎这样的 Razor 并且模型是“SomeObject”类型)

@Html.LabelFor(Function(x) x.HelloMessage)

基本信息http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.resourcetype(v=vs.95).aspx

关于asp.net-mvc - ASP.NET 自定义本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com