Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle line breaks in HTML Encoded MVC view?

I am unsure of the best way to handle this. In my index view I display a message that is contained in TempData["message"]. This allows me to display certain error or informational messages to the user when coming from another action (for example, if a user tries to enter the Edit action when they don't have access, it kicks them back to the Index with a message of "You are not authorized to edit this data").

Prior to displaying the message, I run Html.Encode(TempData["message"]). However, I have recently come into the issue where for longer messages I want to be able to separate the lines out via line breaks (<br>). Unfortunately (and obviously), the <br> gets encoded by Html.Encode so it doesn't cause an actual line break.

How do I process line breaks correctly in Html Encoded strings?

like image 524
KallDrexx Avatar asked Dec 13 '22 19:12

KallDrexx


2 Answers

The easiest solution I've seen is:

@MvcHtmlString.Create(Html.Encode(TempData["message"]).Replace(Environment.NewLine, "<br />"))

If you are using a razor view, you should not have to call Html.Encode normally. By default, Razor html encodes all output. From Scott Gu's blog introducing Razor:

By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.

like image 160
ICodeForCoffee Avatar answered Jan 06 '23 23:01

ICodeForCoffee


I agree with @Roger's comment - there is not really any need to encode anything that you have total control over.

If you still wish to be better safe than sorry (which isn't a bad thing), you could use the Microsoft AntiXss library and use the .GetSafeHtmlFragment(input) method - see HTML Sanitization in Anti-XSS Library

e.g.

<%= AntiXss.GetSafeHtmlFragment(TempData["message"]) %>
like image 40
Charlino Avatar answered Jan 06 '23 21:01

Charlino