Label / Literal control with formatted text field
I found that it is possible to fill 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) that can dynamically hide or show the content. Usually I would fill in those who used:
<asp:Literal ID="Literal1" Text="<%$ Resources:Temp,ContactUs %>" runat="server" />
Now I need the same String.Format functions that the controls still use. I found Display resource value without control over labels or literal data , but that doesn't really work for me, it just writes '<% = GetGlobalResourceObject ("Messages", "ThankYouLabel")%>' on the page (not content. this actual line).
UPDATE:
I found a solution that works with some controls:
<asp:Label runat="server" ID="temp"><%= String.Format(Resources.Temp.TempString, Resources.Contact.PhoneSales) %></asp:Label>
However, this does not work for Literal controls, as they do not allow child controls. I would prefer to keep using Literal as they are the cleanest in terms of generated code so still looking for a solution.
To solve my problem, I have a second look at how I display content and found that many times literals and labels can be removed instead of plain HTML. Then I can use my preferred method <%= ... %>
to display the content.
asp:Literal
doesn't support construction <%= %>
and doesn't allow child controls (I mean something like <asp:Literal runat="server"><%= ... %></asp:Literal>
).
But if you are using data binding, you can use data binding bindings <%# ... %>
:
<asp:Label runat="server" Text="<%# string.Format(...) %>"></asp:Label>
To make this work, you must make sure that you are using implicit or explicit data binding for your controls. Otherwise, such an unbound control does not display anything .
This workaround is a little tricky. Consider using a control, asp:Label
or set the property Text
from the code behind.
You Literal
can use a control instead asp:PlaceHolder
.
PlaceHolders can contain child controls; they also support <%= … %>
-style " expression display ".