4

Why does .Replace(Environment.NewLine, "<br />") give this result:

asdasd<br />waahahahaha<br />asdadsa<br />multiline<br /><br /><br />asdad
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183
paul
  • 567
  • 2
  • 5
  • 11

1 Answers1

7

Probably because there are more than one new line between "multiline" and "asdad".

Example

var someText = string.Format("First line{0}Second line{0}Multiple line breaks{0}{0}{0}some text", Environment.NewLine);

var html = someText.Replace(Environment.NewLine, "<br />");

html will now look like this:

First line<br />Second line<br/>Multiple line breaks<br /><br /><br />some text

Edit

In your case your web page will display the <br /> in the web-browser and not create a new line because it encodes the html output.

What you will need to do is use HtmlString, try this:

<div class="display-field">
    <%: new HtmlString(Model.Body.Replace(Environment.NewLine, "<br />")) %>
</div>

Also see this thread here on StackOverflow talking about "ASP.NET MVC Razor - output HTML string non escaped".

Community
  • 1
  • 1
Filip Ekberg
  • 36,033
  • 20
  • 126
  • 183