开发者

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!


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>


You could try this:

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

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


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.


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


<pre>@myMultiLineString</pre>

OR

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

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


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

and it will work if your using EditorFor()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜