Giovanni Romio
Giovanni Romio

Reputation: 1056

Abusing HTML.Raw

In the current ASP.NET MVC project I'm working I have to manage localized string both in my views and in my server.

Instead of the creating language specific resources the localized string are stored in the database.

A call to the database is performed whenever a localized string is required.

In my .cshtml page I need to display those string.

At the time of coding, resources are specific for just one language (IT) but in future other languages might be specified.

The strings in a specific language might include reserved HTML entities which might wrongly be printed to the user encoded.

To overcome this problem I thought to wrap each string used in Javascript within @Html.Raw() helper even though it may not be necessary.

Eg: @(Html.Raw(localizationService.GetMessage("Success.General"))

That works but I feel like I'm abusing the Html.Raw() method.

Are my doubt completely pointless or could I improve my solution?

Upvotes: 1

Views: 357

Answers (1)

Steve Harris
Steve Harris

Reputation: 5109

You could use a simple static method. Then if you need to change everything globally, you won't have to cope with infinite Html.Raw entries:

public static class Localization
{
    private class HtmlString : IHtmlString
    {
        private string Value;
        public HtmlString(string value)
        {
            Value = value;
        }
        public string ToHtmlString()
        {
            return Value;
        }
    }
    public static IHtmlString Message(string key)
    {
        return new HtmlString(localizationService.GetMessage(key));
    }
}

usage:

@Localization.Message("Success.General");

Upvotes: 2

Related Questions