Changing ResourceManager (Make it Updatable)

1.3k Views Asked by At

I have a project in MVC 3 (Razor) For localization we are using Strongly typed resources. We want to have possibility to update translation that already exist "on-line". It means, that it should be possible to edit translation on the website. (e.g. If in the url there is parameter like "translateLanguage=on") Basically, it is not possible to do that with current solution, because if resource has been changed, then it must be recompiled.

Of course we can write our own Resource Manager that will be using a database, but then we would have to rewrite all of our translations to the database and that would be time consuming. It would also mean that we would have to change all of our code to reflect this "new" resource manager.

It would be hard to implement it in all things. Now, we can use it in attributes e.g.

[Required(ErrorMessageResourceType = typeof(_SomeResource), ErrorMessageResourceName = "SomeResouceElement") 
  SomeProperty

As well as in code:

 string translatedResource = _SomeResource.SomeResourceElement;

Could you provide me with some information how to do this in mvc 3?

1

There are 1 best solutions below

2
On

Generally resource file consists of two parts xml + autogenerated cs code. If you open resource designer file you will see

 /// <summary>
        ///   Looks up a localized string similar to About project.
        /// </summary>
        public static string about_project {
            get {
                return ResourceManager.GetString("about_project", resourceCulture);
            }
        }

So what you can do you can use ResourceManager.GetString("Key")

Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
            var t = Resources.ResourceManager.GetResourceSet(new CultureInfo(cultureName), true, true);

To make it more smart you can rewrite BaseView

public abstract class ViewBase<TModel> : System.Web.Mvc.WebViewPage<TModel>
{
    public string GetTranslation(string key)
    {
        return _rManager.GetString(key);
    }

    private ResourceManager _rManager;
    protected ViewBase()
    {
        _rManager = Resources.ResourceManager.GetResourceSet(new CultureInfo(cultureName), true, true);
    }


}

And then you will be able to use GetTranslation in your razor view (To run this base view you need to modify web.config from Views folder)

And then you will be able after editing xml access to resource data.