ASP.NET custom localization

I've done quite a bit of research and I'm not sure how I should go about doing this.

Normal localization will only change when the language changes, so Hello for french will be Bonjour, but my application needs to have special keywords for specific users, so UserX can say "Hello" should be "Allo".

I would like to have a resource key with IdentityName_resourceKey , and if this key is present, reverse it otherwise, revert to resourceKey .

I think I need a custom ResourceProvider, but my implementation is a simple if statement, so I don't want to write a complete resource provider.

I wrote a DisplayName attribute extension that works great, but it's not very good as I need one of them for each data annotation attribute, and it doesn't work if I use resources directly in pages or controllers ...

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);
        }
    }
}

      

I am looking for the best way to implement this with the least amount of code.

Thank!

+3


source to share


1 answer


There is a better way, data annotation is your answer!

This is just a sample, you need to dig deeper into System.Globalization.CultureInfo and data annotations (System.ComponentModel.DataAnnotations)

you can define your model class as follows (assuming we have a resource file named CustomResourceValues ​​with value "strHello")

public class SomeObject(){

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

}

      



so in our opinion the job should be done with htmlhelper (assuming a razor engine like a render engine and the model is of type "SomeObject")

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

      

Basic info http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.resourcetype(v=vs.95).aspx

0


source







All Articles