Lucifer Sam Lucifer Sam - 4 months ago 85
C# Question

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!

Answer

You could try this:

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

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