Search code examples
c#asp.net-mvchtml-escape-characters

C# Mvc resx escape issue with accented letters


I use resource files in a web project, and sometimes I have accented letters and aphostrophes, which are html-encoded.

So instead of this

Errore: non c'è nessun itemKey definito. L'esecuzione della pagina verrà interrotta..

I see this

Errore: non c'è nessun itemKey definito. L'esecuzione della pagina verrà interrotta..

I know that Html.Raw() can do the trick, but I was wondering if there are some options that can be set in web config to skip the default escaping? Otherwise I'll be forced to add Html.Raw() everywhere

I add resources this way:

@(WmXRexManager.WebResxManager.GetString<SharedVerificationResx>(
    () => SharedVerificationResx.ErrorNoItemKey));

The WebResxManager and the GetString<T>() method are irrelevant because when debugging the resource string is correctly retrieved.


Solution

  • It did not state this explicitly, but I wanted to know the context where the string is being escaped.

    If you use this expression as regular HTML content, the conversion is correct. (you don't need the closing semi-colon, though)

    My guess is (assuming that the error message is output using some JS error handling) that you render the string inside JavaScript, and you need to distinguish between HTML-encoding and JavaScript-encoding, as they differ in some cases.

    I use an HtmlHelper extension method

        public static IHtmlString JsString<TModel>(this HtmlHelper<TModel> html, string s)
        {
            return html.Raw(HttpUtility.JavaScriptStringEncode(s));
        }
    

    which allows to simply write @Html.JSString(stringValue) and have JavaScript strings escaped (inside JS string quotes, of course).