I had a similar problem when I started with localization. If your site has many repeating phrases and words, itβs best to place them in a SharedResource file.
Do this by creating the SharedResource.[LANG_CODE].resx in the Resources folder. Then you need to create a dummy class that you call SharedResource , and put it in the root of the project namespace. Therefore, if your project is called LocalizationTest , then the class will look something like this:
namespace LocalizationTest { public class SharedResource { } }
Then all you have to do to access the shared resource in your model or view is to create an IStringLocalizer<SharedResources> and use it. Like this:
public class HomeController : Controller { private readonly IStringLocalizer<HomeController> _localizer; private readonly IStringLocalizer<SharedResource> _sharedLocalizer; public HomeController(IStringLocalizer<HomeController> localizer, IStringLocalizer<SharedResource> sharedLocalizer) { _localizer = localizer; _sharedLocalizer = sharedLocalizer; } public IActionResult Index() { ViewData["message"] = _sharedLocalizer["Hello!"]; return View(); } }
Or in the view: @inject IViewLocalizer Localizer @inject IStringLocalizer SharedLocalizer
@{ ViewData["Title"] = SharedLocalizer["Hello!"]; } <h1>@Localizer["Welcome message"]</h1>
I skipped the import and used the instructions for brevity.
You can find more detailed information about SharedResource and general localization here: Microsoft documentation or in the answer to the question that I posted here My questions and answers .
source share