在 HTML 中呈现字符串并保留空格和换行符

新手上路,请多包涵

我有一个具有详细信息页面的 MVC3 应用程序。作为其中的一部分,我有一个包含空格和换行符的描述(从数据库中检索)。渲染时,新行和空格将被 html 忽略。我想对这些空格和新行进行编码,这样它们就不会被忽略。

你是怎样做的?

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

原文由 Dan dot net 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 686
2 个回答

只需将内容样式设置为 white-space: pre-wrap;

 div {
    white-space: pre-wrap;
}
 <div>
This is some text   with some extra spacing    and a
few newlines along with some trailing spaces
     and five leading spaces thrown in
for                                              good
measure
</div>

原文由 pete 发布,翻译遵循 CC BY-SA 4.0 许可协议

您是否尝试过使用 <pre> 标签。

  <pre>

    Text with

    multipel line breaks embeded between pre tag

    will work    and
       also tabs..will work

it will preserve the formatting..
    </pre>

原文由 N30 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题