ASP.NET MVC: How do I display multiline text?

View Model:

public class Note
    public string Text { get; set; }

Default editor template renders a <textarea> element with the newlines preserved.

The default display template renders the text as a single string with the newlines removed.

I tried this, but it doesn't work:


@model string

@Html.Raw(Model.Replace(System.Environment.NewLine, "<br />"))

I can do something silly like @Html.Raw(Model.Replace("e", "<br />")) and it will work but of course I only want to replace the newline characters the <br /> element! I also tried using @"\n" and that didn't work either.

Any ideas?



You could try this:

@Html.Raw("<pre>"+ Html.Encode(Model) + "</pre>");

This will preserve your content and show it as-is.

The answer is that you'd do none of this. That's the job of your stylesheet. Basically, render the content any way you want, into a <p>, for example, and use CSS to control how white space is preserved. For example:

(in your style tag, or in your CSS)

p.poem {

(in your HTML markup)

<p class="poem">
    There is a place where the sidewalk ends
    And before the street begins,
    And there the grass grows soft and white,
    And there the sun burns crimson bright,
    And there the moon-bird rests from his flight
    To cool in the peppermint wind.

i would recommend formatting the output with css instead of using consuming server side strings manipulation like .replace,

just add this style property to render multiline texts :

   white-space: pre-line;


<div class="multiline">

newlines will render like br elements.

Try @Html.Raw(Model.Replace("\r\n", "<br />"))



<span style="white-space:pre">@myMultiLineString</span>

No need to do Html.Encode, as it's done by default

public your_property {set; get;}

and it will work if your using EditorFor()

Need Your Help

Why does Comparator declare equals?

java lambda java-8 comparator functional-interface

The Comparator interface has its own equals() method. Any class will get equals() by default through Object class. What is the need to have equals() method inside an interface?

PhpStorm Ignore files/directories in TODO feature

phpstorm todo

Is it possible to exclude certain files from the TODO function in PhpStorm? For example, I'm using the highcharts javascript library. I don't want to see the few dozen or so TODO's they have marked...