如何在ASP.NET Core 7 MVC的Razor视图中获取CSS隔离标识符?
解决ASP.NET Core CSS隔离与DataTables兼容问题
1. 在Razor视图中获取CSS隔离标识符
ASP.NET Core MVC内置了获取当前视图CSS隔离标识符的方法,在你的Index.cshtml中添加以下代码,将标识符存入JavaScript变量:
@{ var cssIsolationId = Microsoft.AspNetCore.Mvc.ViewFeatures.Css.Isolation.GetCssIsolationId(ViewContext); } <script> // 存储CSS隔离属性名,供DataTables回调使用 const cssIsolationAttribute = '@cssIsolationId'; </script>
2. 在DataTables的createdRow回调中添加隔离属性
配置DataTables时,利用createdRow回调函数,为Ajax加载生成的每一行添加上一步获取的隔离属性:
$(document).ready(function() { $('#yourTableId').DataTable({ ajax: '/Home/GetTableData', // 替换为你的数据接口地址 columns: [ // 填写你的列配置,例如: { data: 'Id' }, { data: 'Name' }, { data: 'Description' } ], createdRow: function(row, data, index) { // 为动态生成的行添加CSS隔离属性 row.setAttribute(cssIsolationAttribute, ''); } }); });
3. 验证样式匹配逻辑
你的Index.cshtml.css中的样式会被自动编译为带隔离属性的选择器,例如:
/* 原始隔离CSS */ tr { background-color: #f5f5f5; } tr:hover { background-color: #e9e9e9; }
编译后会变成:
tr[b-abc123xyz] { background-color: #f5f5f5; } tr:hover[b-abc123xyz] { background-color: #e9e9e9; }
通过createdRow添加的属性会让动态行匹配这些编译后的选择器,从而应用隔离样式。
内容的提问来源于stack exchange,提问作者Sam Axe
相关产品推荐
相关产品推荐

