We already mentioned the ASP.NET Resource Files a while ago, praising their usefulness to grant the developers an handy, centralized access to literal and media contents troughout our application projects. This is expecially convenient when developing a multilanguage website, as explained in this post). That being said, it's not uncommon to end up having resource items containing HTML code, like shown in the following screenshot:
As you might already know, if you use this HTML_Response resource in your webpage UI - be it aspx, ascx, cshtml - you will have the exact same output shown by the screenshot, including the HTML elements: that's why the ASP.NET web publishing engine will automatically escape, for security reasons, the resource file textual content, including HTML code, entities and tags.
Luckily enough, there's way to disable the auto-escape, depending on which view engine you've chose to adopt.
Razor
If you're using Razor - which I personally hope for you - all you need to do is to wrap the resource reference inside the @Html.Raw method, just like shown by the following example:
1 2 3 4 5 |
This will work: <span>@Html.Raw(MyNamespace.Resources.Main.HTMLText)</span> This will also work: <span>@Html.Raw(String.Format(MyNamespace.Resources.Main.HTMLFormatText, "yay!"))</span> |
Please notice that, in the latter example, the whole String.Format result - not the resource string by itself - must be used as a parameter of @Html.Raw.
ASP.NET
If you're using ASP.NET you can achieve the same result in two possible ways.
Using the Response.Write ASP.NET shortcut
1 2 3 4 5 |
This will work: <%$ Resources:MyNamespace.Resources.Main.HTMLText %> This will also work: <%= String.Format(global::Resources.Main.HTMLFormatText, "yay!") %> |
Using the <asp:Literal> Control
1 2 3 4 5 |
This will work: <asp:Literal id="lt1" runat="server" Text="<%$ Resources:Main.HTMLText %>" /> This will NOT work: <asp:Literal id="lt1" runat="server" Text="<%= String.Format(global::Resources.Main.HTMLFormatText, "yay!") %>" /> |
Unfortunately, the latter won't work: you'll have to programmatically set it in code-behind like this:
1 2 3 4 |
protected void Page_Load(object sender, EventArgs e) { lt1.Text = String.Format(global::Resources.Main.HTMLFormatText, "yay!"); } |
That's it: happy coding!