代码之家  ›  专栏  ›  技术社区  ›  Alex

ASP.NetMVC-在中显示带换行符的文本

  •  1
  • Alex  · 技术社区  · 15 年前

    我有一些文本,存储在一个表中。 我在用asp.netmvc来显示这个。

    <%=(Model.QuestionBody.Replace("\r\n", "<br/>").Replace ("\r", "<br/>")) %>
    

    像这样,它显示正确 但是,如果省略.Replace,它将在一行上显示所有内容。

    但是,文本框中显示的数据格式正确。

    我的问题是-

    4 回复  |  直到 15 年前
        1
  •  4
  •   ggarber    15 年前

    你可以把你的文字在一个“前”标签。

    <pre>
       <%= Model.QuestionBody %>
    </pre>
    

    但是,通常这种文本以html形式存储在数据库中,包括

        2
  •  2
  •   Community Mohan Dere    9 年前

    我想 this

        3
  •  0
  •   Patricia    15 年前

    这是一种方便的扩展方法,我用它来格式化带有新行的字符串。它是用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()) %>
    
        4
  •  0
  •   Gratzy    10 年前

    @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>
    

    }