MVC4 localization. Accessing resx from view

前端 未结 6 1294
逝去的感伤
逝去的感伤 2020-12-14 20:08

In my view I would like to access resource strings from the specific local resource on that file.. Just as you know it from web-forms:

(string)GetLocalResour         


        
6条回答
  •  被撕碎了的回忆
    2020-12-14 20:47

    terjetyl put me on the right path, but I had to do some "coding" (ah nuts) to get it working. My setup is Visual Studio 2013, MVC 5, Razor.

    1. Right-click on you view's containing folder, select Add > Add ASP.NET folder > App_LocalResources

    2. Add two Resource Files into here: Index.cshtml.resx and Index.cshtml.fr-FR.resx (assuming your view is called "Index" and you want French translations). Check the file properties, and make sure they are set to Build Action=Content and Custom Tool=(blank)

    3. Double-click the resx files and populate with key/values

    4. Create a HtmlHelper extension method.


    public static class HtmlExtensions
    {
        public static MvcHtmlString Translate(this HtmlHelper htmlHelper, string key)
        {
            var viewPath = ((System.Web.Mvc.RazorView)htmlHelper.ViewContext.View).ViewPath;
            var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
    
            var httpContext = htmlHelper.ViewContext.HttpContext;
            var val = (string)httpContext.GetLocalResourceObject(viewPath, key, culture);
    
            return MvcHtmlString.Create(val);
        }
    }
    

    1. Use extension in your view:

      @Html.Translate("MyKey")

    To explain, the helper gets the virtual path of your view and passes it to HttpContext.GetLocalResourceObject(), which decides what resource file to use (and degrades gracefully).

    One last thing, make sure this is in your web.config:

    
        
        ...
    

    I've tried to kept this as simple as possible. However, be aware that by using this example, French cultures other than fr-FR (e.g. fr-CA) will default to the base resx. If you want it to be cleverer than this, more code is needed - I can include on request.

提交回复
热议问题