
Blazorise DataGrid 默认对字符串进行 HTML 编码以防止 XSS,因此直接传入 <a href="https://www.php.cn/link/263b1243ca2dbeb358777ceabc4a2e4c"> 等 HTML 字符串会原样显示。需使用 MarkupString 显式标记为可信 HTML,并结合模板列实现安全、可控的富文本渲染。
blazorise datagrid 默认对字符串进行 html 编码以防止 xss,因此直接传入 `` 等 html 字符串会原样显示。需使用 `markupstring` 显式标记为可信 html,并结合模板列实现安全、可控的富文本渲染。
在 Blazorise 中,DataGrid(如 DataGrid<TItem>)出于安全考虑,不会自动解析 HTML 字符串——所有单元格内容默认以纯文本方式渲染(即调用 @context.SomeProperty 时等价于 @((object)context.SomeProperty),触发 HTML 编码)。若需渲染链接、带样式的文本或内联图标等动态 HTML,必须显式告知 Blazor:该内容已由开发者验证为安全,可作为原始 HTML 插入。
✅ 正确做法:使用 DataGridColumn<TItem> 的 ChildContent 模板 + MarkupString
推荐在 DataGrid 列定义中使用 ChildContent 模板,并在其中将字符串属性转换为 MarkupString:
<DataGrid TItem="Product" Data="@products">
<DataGridColumns>
<DataGridColumn TItem="Product" Field="@nameof(Product.Name)" Caption="名称" />
<!-- ✅ 安全渲染 HTML 链接 -->
<DataGridColumn TItem="Product" Caption="操作">
<ChildContent>
@{
var url = $"https://example.com/product/{context.Id}";
var linkHtml = $"<a href=\"{url}\" class=\"btn btn-sm btn-primary\">查看详情</a>";
<div>@((MarkupString)linkHtml)</div>
}
</ChildContent>
</DataGridColumn>
</DataGridColumns>
</DataGrid>? 提示:@((MarkupString)linkHtml) 中的强制类型转换是关键。Blazor 将跳过编码,直接将字符串作为 HTML 解析并插入 DOM。
⚠️ 注意事项与最佳实践
-
绝不直接信任用户输入:MarkupString 绕过 Blazor 的默认 XSS 防护。若 linkHtml 来源于用户提交、数据库未过滤字段或第三方 API,必须先做白名单清洗(例如使用 HtmlSanitizer 库)。
立即学习“前端免费学习笔记(深入)”;
anything-to-html下载将调研报告、方案对比、数据分析、需求梳理、会议纪要、设计说明、代码评审、学习笔记等任务产物输出为可在浏览器直接打开的单文件 HTML,替代 Markdown 作为最终交付物。Markdown 在信息密度、视觉清晰度和可分享性上已跟不上 AI 产物的丰富度,HTML 能同时承载排版、表格、SVG 等。
-
优先封装为计算属性(推荐):在模型或 ViewModel 中提供预处理后的 MarkupString 属性,提升可读性与复用性:
public class Product { public int Id { get; set; } public string Name { get; set; } // ✅ 安全封装:仅暴露已校验的 HTML public MarkupString ActionLink => new MarkupString( $"<a href=\"/product/{Id}\" target=\"_blank\" rel=\"noopener\">→ 查看</a>"); }对应模板列简化为:
<DataGridColumn TItem="Product" Caption="快捷操作"> <ChildContent>@context.ActionLink</ChildContent> </DataGridColumn> 避免在 Field 属性中使用 HTML:Field="@nameof(Product.HtmlContent)" 仅支持绑定到简单类型(如 string, int),不支持 MarkupString;强行绑定会导致编译错误或空渲染。
? 总结
Blazorise DataGrid 渲染 HTML 的核心在于 “模板化 + MarkupString 显式声明”。通过 ChildContent 自定义单元格内容,并用 (MarkupString) 转换可信 HTML 字符串,即可实现链接、按钮、徽章等富交互效果。务必牢记:安全性责任转移至开发者,生产环境务必对动态 HTML 内容进行严格校验与净化。


















