简体   繁体   中英

.Replace(Environment.NewLine, “<br />”) works on localhost but not when I upload my website to host

I have no idea why is that. Here is my code and it works perfectly when I try it on localhost but when I upload my website my text has no <br /> 's. Why this could happen? And how can I fix this issue with new lines? ( white-space: pre-line; is not a solution for me, it is not working on IE6 and it is messing with my styles)

@Html.Raw(Html.Encode(Model.Body)
.Replace(Environment.NewLine, "<br />"))<br />

我相信这个答案是最好的: https//stackoverflow.com/a/8196219/550975

string result = Regex.Replace(input, @"\r\n?|\n", "<br />");

As BuildStarted mentioned in the comments, the browsers might either send \\r\\n or \\n , which will break, if you use Environment.NewLine - and I don't think asp.net will fix that up before running your code.

I'd suggest you use a regular expression to replace linebreaks instead: "\\\\r?\\\\n" This should match both cases (I don't expect any browser to actually use '\\r' only).

A lot has happened since IE6 (thank god!) so I would just like mention the CSS solution to the problem.

In your C#:

ViewBag.StringText = "some text" + Environment.NewLine + "more text in a new line";

In your CSS:

.newlines { 
  white-space:pre-line; 
}

In your Razor:

<div class="newlines">@ViewBag.StringText</div>

不要使用Environment.NewLine ,请尝试以下方法:

someString.Replace(@"\r\n", "<br/>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM