2

I have some text, stored in a table. I'm using asp.net mvc to display this.

One of my views, has the following:

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

Like this, it displays correctly However, if I omit the .Replace, it displays all on one line.

The same data displayed in a TextBox however, displays properly formatted.

My question is- Is there a better way of displaying the text in my View?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Alex
  • 37,502
  • 51
  • 204
  • 332

4 Answers4

5

You can put your text in a "pre" tag.

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

However usually this kind of text is stored in the database as html including the
tags.

ggarber
  • 8,300
  • 5
  • 27
  • 32
2

I think this is the same issue isn't it? If so, solution could be the same.

Community
  • 1
  • 1
alexber
  • 647
  • 1
  • 5
  • 9
1

Best method... No conversions...

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

}

Zonus
  • 2,313
  • 2
  • 26
  • 48
0

this is a handy dandy extention method i use to format strings with new lines. it's in vb, so if your a c# type person it'll neeed some tweaking. but it works and keeps the views tidy.

        <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

so then in your view you would have:

<%=(Model.QuestionBody.FormatForDisplay()) %>
Patricia
  • 7,752
  • 4
  • 37
  • 70