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

时间:2011-09-23 00:08:31

标签: c# asp.net-mvc razor

查看型号:

public class Note
{
    [DataType(DataType.MultilineText)]
    public string Text { get; set; }
}

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

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

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

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

@model string

@Html.Raw(Model.Replace(System.Environment.NewLine, "<br />"))

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

有什么想法吗?

谢谢!

6 个答案:

答案 0 :(得分:25)

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

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

p.poem {
   white-space:pre;
}

(在您的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>

答案 1 :(得分:18)

你可以试试这个:

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

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

答案 2 :(得分:10)

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

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

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

然后

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

换行符将呈现为 br 元素。

答案 3 :(得分:4)

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

答案 4 :(得分:3)

<pre>@myMultiLineString</pre>

OR

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

无需执行Html.Encode,因为默认情况下已完成

答案 5 :(得分:0)

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

如果您使用EditorFor()

,它将会有效
相关问题