ASP.NET MVC:如何显示多行文本?

Luc*_*Sam 12 c# asp.net-mvc razor

查看型号:

public class Note
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

默认编辑器模板呈现<textarea>保留换行符的元素.

默认显示模板将文本呈现为单个字符串,并删除换行符.

我试过这个,但它不起作用:

〜/查看/共享/ EditorTemplates/MultilineText.cshtml

@model string

@Html.Raw(Model.Replace(System.Environment.NewLine, "<br />"))
Run Code Online (Sandbox Code Playgroud)

我可以做一些愚蠢的事情@Html.Raw(Model.Replace("e", "<br />")),它会起作用但当然我只想替换<br />元素的换行符!我也试过使用@"\n",但也没用.

有任何想法吗?

谢谢!

Dav*_*kle 26

答案是你不会这样做.这是样式表的工作.基本上,以任何您想要的方式呈现内容<p>,例如,并使用CSS来控制如何保留空白区域.例如:

(在你的样式标签中,或在你的CSS中)

p.poem {
   white-space:pre;
}
Run Code Online (Sandbox Code Playgroud)

(在您的HTML标记中)

<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>
Run Code Online (Sandbox Code Playgroud)


sca*_*tag 20

你可以试试这个:

@Html.Raw("<pre>"+ Html.Encode(Model) + "</pre>");
Run Code Online (Sandbox Code Playgroud)

这将保留您的内容并按原样显示.


Cht*_*lek 11

我建议使用css格式化输出,而不是使用像.replace那样使用服务器端字符串操作,

只需添加此样式属性即可呈现多行文本:

.multiline
{
   white-space: pre-line;
}
Run Code Online (Sandbox Code Playgroud)

然后

<div class="multiline">
  my
  multiline
  text
</div>
Run Code Online (Sandbox Code Playgroud)

换行符将像br元素一样呈现.


Val*_*mas 5

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