Click here to Skip to main content
15,886,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a text field, lets assume user writes a string:
Example text.
Etc.

It's saved to string as:
Example text. \r\n\r\nEtc.

When you try to display it, it will look like this:
Example text.  Etc.

Simply it ignores all the details that ensure the string is displayed properly. How to display it the way it was in input? I want to display it inside
HTML
<p></p>


What I have tried:

Tried to replace \n and \r with
HTML
<br>
it doesn't work. I'm out of ideas. Looks like ASP.NET does not support it but that seems unlikely.
Posted
Updated 29-Mar-21 3:21am
v4
Comments
Richard MacCutchan 28-Mar-21 5:24am    
Where is the code that does the replacement?
Member 15047625 28-Mar-21 5:33am    
.Replace() inside controller and view, both versions change nothing.
Richard MacCutchan 28-Mar-21 5:39am    
Well I am sorry but there is no way I can guess from a single method call what is happening in your code. Please provide proper details.
Member 15047625 28-Mar-21 5:51am    
string.Replace(Environment.NewLine, "< br>"). "\n" and "\r\n" also does not change the output.

P.S

There is no space in br but here br gets removed for reasons somewhat known.
Richard MacCutchan 28-Mar-21 5:53am    
Yes, because the Replace method returns the new modified string: String.Replace Method (System) | Microsoft Docs[^].

Set style="white-space:pre-line;" on the containing element:
Razor
<div style="white-space:pre-line;">
    @Model.MyText
</div>
white-space - CSS: Cascading Style Sheets | MDN[^]

Or use a custom helper method, such as the one described in this StackOverflow answer[^]:
C#
public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
    if (string.IsNullOrEmpty(content) || html is null)
    {
        return null;
    }

    TagBuilder brTag = new TagBuilder("br");
    IHtmlContent br = brTag.RenderSelfClosingTag();
    HtmlContentBuilder htmlContent = new HtmlContentBuilder();

    // JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
    string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
    string[] lines = lfContent.Split('\n', StringSplitOptions.None);
    foreach(string line in lines)
    {
        _ = htmlContent.Append(line);
        _ = htmlContent.AppendHtml(br);
    }

    return htmlContent;
}
 
Share this answer
 
Try it this way:

XML
<%=myText.Replace("\r\n", "<br/>")%>
 
Share this answer
 
Comments
Member 15047625 28-Mar-21 6:43am    
<%=@item.Body.Replace("\r\n", "br/")%> (br with <>)

Now the output looks like this:

<%=Example text. br/br/Etc.%>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900