渲染HTML中的字符串并保留空格和换行符

我有一个带有详细信息页面的MVC3应用程序。作为其一部分,我有一个描述(从数据库检索),其中有空格和换行符。呈现时,新行和空格将被html忽略。我想对这些空格和换行进行编码,以免被忽略。

你是怎样做的?

我尝试了HTML.Encode,但最终显示了编码(甚至不是在空格和换行符上,而是在其他一些特殊字符上)


一只斗牛犬
浏览 2508回答 3
3回答

繁华开满天机

只需使用设置样式white-space: pre-wrap;。div {&nbsp; &nbsp; white-space: pre-wrap;}<div>This is some text&nbsp; &nbsp;with some extra spacing&nbsp; &nbsp; and afew newlines along with some trailing spaces&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;and five leading spaces thrown infor&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; goodmeasure&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</div>

猛跑小猪

您可能要用&amp;nbsp;(不间断空格)替换所有空格,并\n用<<b></b>br>(html中的换行符)替换所有新行。这样可以达到您想要的结果。body = body.replace(' ', &amp;nbsp;).replace('\n', '<<b></b>br>');那种性质的东西。
打开App,查看更多内容
随时随地看视频慕课网APP