Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 : - Using database instead of resource files as the localization store

We have localised strings in the database and would like to know if extending the ASP.NET Resource Provider Model would work with the ASP.NET MVC 3 Razor view engine.

Kindly let me know if ASP.NET MVC 3 Razor view engine supports retrieving localized strings from the database once we have extended the ASP.NET Resource Provider model. Or does it work only with Classic ASP.NET and not with ASP.NET MVC.

Thank you

Satyaprakash J

like image 829
Satyaprakash J Avatar asked Dec 19 '11 14:12

Satyaprakash J


1 Answers

The cleanest solution I've found so far is: http://www.codeproject.com/Tips/514321/A-Simple-and-Effective-Way-to-Localize-ASP-Net-MVC.

Comments/Feedback are welcomed.

Edit 1: Based on comments, I added code examples and used the link as reference.

I created a customDataAnnotationsProvider class:

public class CustomDataAnnotationsProvider: DataAnnotationsModelMetadataProvider
{
    private ResourceManager resourceManager = new ResourceManager();
    protected override ModelMetadata CreateMetadata(
                         IEnumerable<Attribute> attributes,
                         Type containerType,
                         Func<object> modelAccessor,
                         Type modelType,
                         string propertyName)
    {
        string key = string.Empty;
        string localizedValue = string.Empty;


        foreach (var attr in attributes)
        {
            if (attr != null)
            {
                if (attr is DisplayAttribute)
                {
                    key = ((DisplayAttribute)attr).Name;
                    if (!string.IsNullOrEmpty(key))
                    {
                        localizedValue = resourceManager.GetLocalizedText(key);
                        ((DisplayAttribute)attr).Name = localizedValue;
                    }
                }
                else if (attr is ValidationAttribute)
                {
                    key = ((ValidationAttribute)attr).ErrorMessage;
                    if (!string.IsNullOrEmpty(key))
                    {
                        localizedValue = resourceManager.GetLocalizedText(key);
                        ((ValidationAttribute)attr).ErrorMessage = localizedValue;
                    }
                }
            }
        }
        return base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
    }
}

Then I referenced the custom provider on ApplicationStart in Global.asax

ModelMetadataProviders.Current = new Project.Web.Helpers.CustomDataAnnotationsProvider();

You do not have to change your model and can use the Display annotation:

[Display(Name = "CustomerAccountNumber")]
public string CustomerAccountNumber { get; set; }
like image 149
Nishzone Avatar answered Jun 19 '23 21:06

Nishzone