HTML Formatting in .NET Resource Strings

HTML Formatting in .NET Resource Strings

Whilst working on a client website, and I was adding content to the page based on the provided mockups and designs. All was going fine except for one part – a few paragraphs of content had formatting in the middle. Some had bold words, some had links etc.
This was a problem because I was storing all content in resource strings to allow for easier localisation.
One solution is to split the content into multiple parts, and you can apply the formatting around that, but I don’t think that’s ideal.
While it removes any html code from the content if you get it translated, I find it can also lead to a lack of context so you might not get the translation you’re after.
I also find it quite messy having to place multiple strings together around the formatting on the View, much easier to just have one string.

A (fairly quick) search around the net didn’t reveal the solution, but got me half way there. So I thought I’d quickly document the steps needed to be able to use the resource strings, and still have HTML formatting applied.

For a simple example, the string I might be trying to use could be:
Hello, my name is <strong>Ian Rufus</strong> and I love .NET!  and be in my resources under the name MyContentString
Firstly, when writing the content on the View, don’t just use the string with @Strings.MyContentString
Instead, use @Html.Raw(@Strings.MyContentString) which allows us to render unencoded HTML.

This alone won’t get any formatting applied, we also require a basic change to the resource string.
Instead of the <strong>Ian Rufus</strong>
part of the content string I’m using, we need to replace the angular brackets with the HTML code for that symbol, which is &lt; for < and &gt; for >.
This will give you the full string as Hello, my name is <strong>Ian Rufus</strong> and I love .NET!
This site is a great resource for finding the HTML codes you’ll be after.

And that’s it. The combination of using @Html.Raw() and using HTML codes in the resource string are all you need, and formatting will now be displayed correctly on the View.

Hope that’s helpful!