Reputation: 38499
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?
Upvotes: 2
Views: 5288
Reputation: 2908
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>
}
Upvotes: 1
Reputation: 687
I think this is the same issue isn't it? If so, solution could be the same.
Upvotes: 2
Reputation: 7802
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()) %>
Upvotes: 0
Reputation: 8360
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.
Upvotes: 5