How do I access GetGlobalResourceObject function from a class that is not a page?
-
12-09-2019 - |
Question
I have a class in my asp.net proj, I would like to get access GetGlobalResourceObject (that page exposes), from anywhere in the site, possible?
In other words I wanna access the global resources from a class that is not a page I don't care how.
Solution
Answer: Yes, as following pseudo:
Resources.<The name of the resources file name>.<your resource key>;
Example:
lblTitle.Text = Resources.MySettings.WebsiteTitle;
Resources
is an Visual-Studio auto generated namespace that exposes all the global resource classes and props in the project.
OTHER TIPS
You should use
HttpContext.GetGlobalResourceObject("myResourceKey")
...because that way it will still work when using a custom ResourceProvider. The default type-generator for Resource files explicitely uses the Resx provider and won't work if you implement something like a database provider.
If you are in the site you have access to HttpContext and can use:
HttpContext.GetGlobalResourceObject("myResourceKey")
On some farms you'll need to wrap the call to
HttpContext.GetGlobalResourceObject("myResourceKey")
inside a try/catch block to get it over the "Could not find any resources appropriate for the specified culture or the neutral culture" error.
I kinda took this from the resource designer,
ResourceManager temp =
new ResourceManager("Resources.<<resource name>>",
System.Reflection.Assembly.Load("App_GlobalResources"));