You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC Razor视图中格式化显示带项目符号的数据库内容

问题描述

我的数据库里存着带项目符号的记录,但在Razor页面视图中展示时,所有项目符号项都连成了一行:

 Measures 24”x10”x12” or 2,800 cubic inches of storage space  3 layer laminated polyester waterproof fabric  Commercial grade zipper  Reinforced steel frame closure  Extra heavy duty bottom panel  5 exterior pockets  6 interior pockets  Writable name plate

我需要让它显示为每个项目符号单独一行的格式:

 Measures 24”x10”x12” or 2,800 cubic inches of storage space
 3 layer laminated polyester waterproof fabric
 Commercial grade zipper
 Reinforced steel frame closure
 Extra heavy duty bottom panel
 5 exterior pockets
 6 interior pockets
 Writable name plate

补充:用户可以在描述框粘贴带格式的内容,但保存到数据库后就变成了无换行的单个字符串,导致展示异常。

解决方案

1. 后端C#处理(推荐)

在从数据库读取数据后,把连续的项目符号分割并转换成HTML结构,再用Html.Raw渲染:

方法A:转成HTML无序列表

生成标准列表结构,样式更易控制:

// 假设从数据库取出的字段名为ItemDescription
var rawDescription = dbItem.ItemDescription;
// 按项目符号分割内容,过滤空项
var listItems = rawDescription.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
// 拼接成<ul><li>结构
var formattedDescription = "<ul>" + string.Join("</li><li>", listItems) + "</li></ul>";

Razor视图中渲染:

@Html.Raw(formattedDescription)
方法B:直接添加HTML换行标签

保留原项目符号样式,仅拆分换行:

var rawDescription = dbItem.ItemDescription;
// 给每个项目符号前加<br>,去掉开头多余的换行
var formattedDescription = rawDescription.Replace(" ", "<br> ").TrimStart('<','b','r','>',' ');

视图中渲染:

@Html.Raw(formattedDescription)

2. 前端JavaScript处理

不想修改后端逻辑时,可在页面加载后动态处理:

<div id="itemDescription">@Model.ItemDescription</div>

<script>
    const descEl = document.getElementById('itemDescription');
    let content = descEl.innerHTML;
    // 全局替换项目符号前的位置为换行+项目符号
    content = content.replace(/ /g, '<br> ');
    // 移除开头可能出现的多余<br>
    if (content.startsWith('<br>')) {
        content = content.slice(4);
    }
    descEl.innerHTML = content;
</script>

3. 优化保存逻辑(根源解决)

如果能修改数据保存流程,建议保留用户输入的换行符:

  • 前端提交时,不要过滤输入中的换行(\n);
  • 后端直接将含换行的字符串存入数据库;
  • 展示时把换行符转成HTML换行标签:
    var formattedDescription = Model.ItemDescription.Replace("\n", "<br>");
    
    再用Html.Raw渲染,完全保留用户输入的格式结构。

注意:处理时要确认项目符号的字符是否统一(比如可能是•或),若有多种符号,需调整分割/替换的匹配规则。

内容的提问来源于stack exchange,提问作者DonDavid12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:52:37