Jeff Camera
Jeff Camera

Reputation: 5544

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

View Model:

public class Note
{
    [DataType(DataType.MultilineText)]
    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:

~/Views/Shared/EditorTemplates/MultilineText.cshtml

@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?

Thanks!

Upvotes: 14

Views: 37303

Answers (6)

Ahmad Tarabeshi
Ahmad Tarabeshi

Reputation: 173

 [DataType(DataType.MultilineText)]
public your_property {set; get;}

and it will work if your using EditorFor()

Upvotes: 1

Dave Markle
Dave Markle

Reputation: 97671

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 {
   white-space:pre;
}

(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.
</p>

Upvotes: 28

Philipp Munin
Philipp Munin

Reputation: 5903

<pre>@myMultiLineString</pre>

OR

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

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

Upvotes: 3

Chtioui Malek
Chtioui Malek

Reputation: 11515

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 :

.multiline
{
   white-space: pre-line;
}

then

<div class="multiline">
  my
  multiline
  text
</div>

newlines will render like br elements.

Upvotes: 11

scartag
scartag

Reputation: 17680

You could try this:

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

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

Upvotes: 22

Valamas
Valamas

Reputation: 24719

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

Upvotes: 5

Related Questions