Resource file for a Custom ASP.net control (.ascx)

2019-06-02 22:51发布

问题:

I have a control containing some text which I want to get from a resx file, I thought I could just create a file called ControlName.ascx.resx but that doesn't seem to be working.

I'm using

label1.InnerText = (string)GetLocalResourceObject("default");

To get the value from the resource file but it keeps throwing up an InvalidOperation Exception.

Am I right about how resx files work or does it only work for Pages?

I have the same code working on an aspx page.

回答1:

When you call GetLocalResourceObject from within a user control, you are actually calling TemplateControl.GetLocalResourceObject, which will look in the wrong place for the resource file. You need to call HttpContext.GetLocalResourceObject instead.

protected string HttpContextGetLocalResourceObjectAsString(string message)
{
  string path = HttpContext.Current.Request.Path;
  return (HttpContext.GetLocalResourceObject(path, message) as string);
}

Now you can do

label1.InnerText = HttpContextGetLocalResourceObjectAsString("default");


回答2:

Per the documentation:

Gets a page-level resource

http://msdn.microsoft.com/en-us/library/system.web.httpcontext.getlocalresourceobject.aspx

Edit- added

It may be less work to just add the string to the web.config and grab it from there.

<configuration>
  <appSettings>
    <add key="LoggingSystemId" value="B2F085A9-6EC1-4CBF-AF8B-B17BFA75AD81"/>
  <appSettings>
...

referenced as follows:

logger.SystemId = System.Configuration.ConfigurationManager.AppSettings["LoggingSystemId"];

Of course, you'll need a reference to the System.Configuration dll.



回答3:

A year or so later, but i think this is what you're after?

var resource = HttpContext.GetLocalResourceObject(TemplateControl.AppRelativeVirtualPath, termType.ToString());

Mark answer if that's the one!