ASP.NET Core Razor Pages局部视图jQuery DataTables样式不生效
问题描述
在ASP.NET Core Razor Pages项目中,使用搭载jQuery DataTables的局部视图展示客户列表时,业务逻辑可正常运行,但出现DataTables样式未生效、搜索控件不显示的异常。已按要求添加所有依赖资源引用,相同实现代码在JS Fiddle示例中可正常运行,迁移到Razor Pages项目后异常稳定复现。经浏览器Network面板检查,所有静态资源均加载正常,各相关文件代码如下:
_Layout.cshtml 代码
<html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>@View ViewBag.Title</title> <link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet"/> </head> <body class="sb-nav-fixed"> @RenderBody() <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script> </body> </html>
Customers.cshtml 页面代码
@model Web.Pages.Customer.CustomersModel @{ ViewData["Title"] = "Registration"; } <div class="card"> <div class="col-sm-12" style="padding:20px"> <a onclick="jQueryModalGet('?handler=CreateOrEdit','New Customer')" class="btn btn-success"> 新建 </a> <a id="reload" class="btn bg-warning"> 刷新 </a> </div> <div id="viewAll" class="card-body table-responsive"></div> </div> @section Scripts { <script> $(document).ready(function () { $('#viewAll').load('?handler=ViewAllPartial'); }); $(function () { $('#reload').on('click', function () { $('#viewAll').load('?handler=ViewAllPartial'); }); }); </script> }
CustomersModel.cs 代码
public class CustomersModel : PageModel { private readonly ICustomerRepository _customer; private readonly IUnitOfWork _unitOfWork; private readonly IRazorRenderService _renderService; private readonly ILogger<CustomersModel> _logger; public CustomersModel(ILogger<CustomersModel> logger, ICustomerRepository customer, IRazorRenderService renderService) { _logger = logger; _customer = customer; _renderService = renderService; } public IEnumerable<Core.Entities.Customer> Customers { get; set; } public IEnumerable<CustomerModel> CustomerModel{ get; set; } public void OnGet() { } public PartialViewResult OnGetViewAllPartial() { CustomerModel = _customer.GetAsync(); return new PartialViewResult { ViewName = "_ViewAll", ViewData = new ViewDataDictionary<IEnumerable<CustomerModel>>(ViewData, CustomerModel) }; } }
_ViewAll.cshtml 局部视图代码
@model IEnumerable<CustomerModel> <table class="display" id="#dataTable"> <thead> <tr> <th>名</th> <th>姓</th> <th>年龄</th> <th>手机号</th> <th>地址</th> </tr> </thead> <tbody> @if (Model.Count() != 0) { @foreach (var customer in Model) { <tr> <td>@customer.FirstName</td> <td>@customer.LastName</td> <td>@customer.Age</td> <td>@customer.PhoneNumber</td> <td>@customer.Address</td> </tr> } } </tbody> </table> <script> $(document).ready(function () { $("#dataTable").DataTable(); }); </script>
故障原因
核心问题是表格DOM的id属性写法错误:
局部视图_ViewAll.cshtml中给table标签设置id时,错误将jQuery选择器专用的#符号写入了id属性值,导致页面实际渲染出的表格id为#dataTable,后续初始化代码使用$("#dataTable")选择器完全匹配不到目标表格元素,DataTables初始化逻辑从未执行,因此默认样式、搜索框、分页等控件都不会生成。
另外还存在两个潜在问题:
_Layout.cshtml中title标签存在Razor语法笔误,多余的@View标记会导致页面标题渲染异常- DataTables初始化代码写在通过jQuery
load()异步加载的局部视图中,存在时序风险,点击刷新按钮重载局部内容时还可能出现重复初始化报错
修复步骤
- 修正表格id属性
打开_ViewAll.cshtml,修改table标签的id属性,去掉多余的#符号:
<!-- 错误写法 --> <table class="display" id="#dataTable"> <!-- 正确写法 --> <table class="display" id="dataTable">
- 修正布局页语法笔误
打开_Layout.cshtml,修改title标签为正确写法:
<!-- 错误写法 --> <title>@View ViewBag.Title</title> <!-- 正确写法 --> <title>@ViewBag.Title</title>
- (推荐优化)调整DataTables初始化逻辑位置
将初始化逻辑从局部视图移到主页面的Scripts块中,绑定到load()方法的完成回调,避免时序问题和重复初始化报错:
首先删除_ViewAll.cshtml底部的DataTables初始化script块,然后修改Customers.cshtml的Scripts块代码:
@section Scripts { <script> function initDataTable() { // 已初始化则先销毁,避免重载时报错 if ($.fn.DataTable.isDataTable('#dataTable')) { $('#dataTable').DataTable().destroy(); } $('#dataTable').DataTable(); } $(document).ready(function () { $('#viewAll').load('?handler=ViewAllPartial', initDataTable); }); $(function () { $('#reload').on('click', function () { $('#viewAll').load('?handler=ViewAllPartial', initDataTable); }); }); </script> }
修改完成后刷新页面,DataTables即可正常加载样式、搜索框、分页等所有功能。
内容的提问来源于stack exchange,提问作者aman girma
相关产品推荐
相关产品推荐

