Search code examples
c#localizationasp.net-3.5app-globalresources

Can we use Resource Expressions in javascript and other parts except Literal?


The Literal control works all the time

<asp:Literal ID="Literal7" runat="server" 
    Text="<%$ Resources:ErrorMessages, errorCompanyNotFound %>" />

But if I want to use this as a parameter in an image, like

<img src="blahblah" alt="" 
    title"<%$ Resources:ErrorMessages, errorCompanyNotFound %>" />

It gives the annoying error

Literal expressions like '' are not allowed. Use instead.

Same happens if I try to access it through Javascript

var noHit = '<%$ Resources:ErrorMessages, errorCompanyNotFound %>';

Does anyone had any idea how can I fetch the Global Resource value under this circumstances?


Solution

  • The only way I could find to work correctly was to use a public method instead the <%$ call.

    in code behind I did:

    public string GetResource(string ResourceName, string ResourceKey)
    {
        string r = HttpContext.GetGlobalResourceObject(ResourceName, ResourceKey) as string;
        if (r == null)
            return ResourceKey;
        return r;
    }
    

    then was as easy as call it:

    <img src="blahblah" alt="" 
        title"<%= GetResource("ErrorMessages", "errorCompanyNotFound") %>" />
    

    and

    var noHit = '<%= GetResource("ErrorMessages", "errorCompanyNotFound") %>';
    

    I hope this helps someone like me :)