简体   繁体   English

.Replace(Environment.NewLine,“ <br /> “)在localhost上工作,但在我将网站上传到主机时则不行

[英].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. 这是我的代码,当我在localhost上尝试它时,它运行得很好但是当我上传我的网站时,我的文字没有<br /> 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) white-space: pre-line;对我来说不是一个解决方案,它不适用于IE6而且它正在弄乱我的风格)

@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. 正如BuildStarted在评论中提到的那样,如果你使用Environment.NewLine ,浏览器可能会发送\\r\\n\\n ,这会破坏 - 我不认为asp.net会在运行你的代码之前修复它。

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). 我建议您使用正则表达式替换换行符: "\\\\r?\\\\n"这应该匹配两种情况(我不希望任何浏览器实际上只使用'\\ r')。

A lot has happened since IE6 (thank god!) so I would just like mention the CSS solution to the problem. 自IE6以来发生了很多事情(感谢上帝!)所以我想提一下这个问题的CSS解决方案。

In your C#: 在你的C#中:

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

In your CSS: 在你的CSS中:

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

In your Razor: 在你的剃刀:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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