Question

I have discovered that it is possible to populate resource strings with variable information using string.format, see below:

String.Format(Resources.Temp.TempString, Resources.Contact.PhoneSales)

I can display this on my page using:

<p><%= String.Format(Resources.Temp.TempString, Resources.Contact.PhoneSales) %></p>

In some cases I have a Label or Literal (or any control) which might dynamically hide or show content. Ordinarily I would populate those using:

<asp:Literal ID="Literal1" Text="<%$ Resources:Temp,ContactUs %>" runat="server" />

I now would like the same String.Format functionality whilst still using controls. I found Display value of Resource without Label or Literal control but this doesn't actually work for me, it just writes out '<%= GetGlobalResourceObject("Messages", "ThankYouLabel") %>' on the page (not the content, that actual string).

UPDATE:

I have found a solution which works with some controls:

<asp:Label runat="server" ID="temp"><%= String.Format(Resources.Temp.TempString, Resources.Contact.PhoneSales) %></asp:Label>

However, this works doesn't work for Literal controls as they don't allow child controls. I'd prefer to keep using Literal's as they are the cleanest in terms of code generated, so still seeking a solution.

Was it helpful?

Solution 2

To solve my problem I have actually had a second look at how I am displaying content and found that a lot of times the Literals and Labels could be dropped in place of plain HTML code. I can then use my preferred method <%= ... %> to display content.

OTHER TIPS

asp:Literal doesn't support <%= %> construct, and doesn't allow child controls (I mean something like <asp:Literal runat="server"><%= ... %></asp:Literal>).

But if you use data binding, your could use data-binding expresions <%# ... %>:

<asp:Label runat="server" Text="<%# string.Format(...) %>"></asp:Label>

To make this work you should ensure that either implicit or explicit data binding for your controls is used. Otherwise the control like this without binding outputs nothing.

This workaround is a little bit complex. Consider using either asp:Label control, or set the Text property from the code behind.

You could use an asp:PlaceHolder control instead of a Literal.
PlaceHolders can contain child controls; they also support <%= … %>-style "displaying expressions".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top