Skip to content Skip to sidebar Skip to footer

Asp.net Mvc Html.encode - New Lines

Html.Encode seems to simply call HttpUtility.HtmlEncode to replace a few html specific characters with their escape sequences. However this doesn't provide any consideration for ho

Solution 1:

HtmlEncode is only meant to encode characters for display in HTML. It specifically does not encode whitespace characters.

I would go with your first option, and make it an extension method for HtmlHelper. Something like:

publicstaticstringHtmlEncode(this HtmlHelper htmlHelper,
                                string text, 
                                bool preserveWhitespace)
{
    // ...
}

You could use String.Replace() to encode the newlines and spaces (or Regex.Replace if you need better matching).

Solution 2:

Using the style="white-space:pre-wrap;" worked for me. Per this article.

Solution 3:

If you use Razor you can do:

@MvcHtmlString.Create(Html.Encode(strToEncode).Replace(Environment.NewLine, "<br />"))

in your view, or in your controller:

HttpServerUtilityhttpUtil=newHttpServerUtility();
MvcHtmlStringencoded= httpUtil.HtmlEncode(strToEncode).Replace(Environment.NewLine, "<br />");

I have not tested the controller method, but it should work the same way.

Solution 4:

Put your output inside <pre></pre> and/or <code></code> blocks. E.g:

<pre>@someValue</pre> /<code>@someValue</code>

Use the equivalent css on an existing div:

<divstyle="white-space:pre-wrap;">@someValue</div>

Depends whether you want the semantic markup or whether you want to fiddle with css. I think these are both neater than inserting <br/> tags.

Solution 5:

///<summary>/// Returns html string with new lines as br tags///</summary>publicstatic MvcHtmlString ConvertNewLinesToBr<TModel>(this HtmlHelper<TModel> html, string text)
    {
        returnnew MvcHtmlString(html.Encode(text).Replace(Environment.NewLine, "<br />"));
    }

Post a Comment for "Asp.net Mvc Html.encode - New Lines"