我有一些文本,存储在表格中。 我正在使用asp.net mvc来显示它。
我的一个观点如下:
<%=(Model.QuestionBody.Replace("\r\n", "<br/>").Replace ("\r", "<br/>")) %>
像这样,它会正确显示 但是,如果省略.Replace,它会在一行中显示所有内容。
然后,TextBox中显示的相同数据显示格式正确。
我的问题是 - 有没有更好的方法在我的视图中显示文本?
答案 0 :(得分:4)
您可以将文字放在“预先”标签中。
<pre>
<%= Model.QuestionBody %>
</pre>
然而,通常这种文本作为html存储在数据库中,包括
标签。
答案 1 :(得分:2)
我认为this是同一个问题不是吗?如果是这样,解决方案可能是相同的。
答案 2 :(得分:0)
这是一个方便的花花公子扩展方法,我用它来格式化新行的字符串。它是在vb中,所以如果你是一个c#类型的人,它将需要一些调整。但它的工作原理并使观点保持整洁。
<Extension()> _
Public Function FormatForDisplay(ByVal stringToFormat As String) As String
If Not String.IsNullOrEmpty(stringToFormat) Then
stringToFormat = Replace(stringToFormat, vbCrLf, "<br />")
stringToFormat = Replace(stringToFormat, vbCr, "<br />")
stringToFormat = Replace(stringToFormat, vbLf, "<br />")
Return stringToFormat
End If
Return stringToFormat
End Function
那么在你看来你会有:
<%=(Model.QuestionBody.FormatForDisplay()) %>
答案 3 :(得分:0)
最好的方法......没有转换......
@model MyNameSpace.ViewModels.MyViewModel
@{
ViewBag.Title = "Show formatted text";
}
@using (Html.BeginForm())
{
<div class="h3">
<span style="white-space: pre-wrap">@Model.myText</span>
</div>
}