Reputation: 5544
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
Reputation: 173
[DataType(DataType.MultilineText)]
public your_property {set; get;}
and it will work if your using EditorFor()
Upvotes: 1
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
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
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
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