views:

84

answers:

3

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?

A: 

"Process" the message in the controller:

  1. HTMLEncode the message
  2. Insert the line break tags
  3. Add message to the TempData collection.
Dave Swersky
I think I'd rather Encode the message in the view. I think encoding in the controller is risky, as you have to make sure you do it everywhere that redirects to the Index action. It's easier to forget one spot.
KallDrexx
A: 

StringBuilder sb = new StringBuilder();

foreach(string message in messages) { sb.Append(string.Format("{0}
", Server.HtmlEncode(message)); }

TempData["message"] = sb.ToString();

Andy Evans
+1  A: 

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"]) %>

HTHs,
Charles

Charlino
Oh that is perfect. I can use that in other areas of my code as well where I want to preserve line breaks. Thanks!
KallDrexx