asp.net - Cannot load script in ViewComponent
问题描述
I created a ViewComponent
which display a Table
that require some plugin for enable specific functionalities. Inside the ViewComponent
I tried to create a specific section:
@section DataTableScripts{
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
unfortunately I discovered that a ViewComponent
cannot load a @section
.
So I tried to include the script directly in the ViewComponent
, but the problem is that the scripts are loaded before of JQuery
which is loaded inside the _Layout
, specifically:
ViewComponent
<script src="~/js/JQuery/jquery.dataTables.js"></script>
<script src="~/js/JQuery/dataTables.buttons.min.js"></script>
<script src="~/js/JQuery/dataTables.keyTable.min.js"></script>
<script src="~/js/JQuery/dataTables.responsive.min.js"></script>
<script src="~/js/JQuery/dataTables.select.min.js"></script>
<script src="~/js/JQuery/dataTables.bootstrap4.js"></script>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
Layout
<script src="~/js/jquery.min.js"></script>
so in this case I'll get:
jQuery is not defined
How can I manage this situation?
解决方案
只需Layout
为您的 ViewComponent 设置。
@{
Layout = "/Views/Shared/_Layout.cshtml";
}
@section DataTableScripts{
<div>It works </div>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
这是有效的屏幕截图:
[编辑]
这种方法似乎不是一个好方法。正如@Kirk Larkin所说,这将使Layout
渲染两次。另一个补丁是编写一个新RefinedLayout.cshtml
的并将Layout
of设置ViewComponent
为RefinedLayout
:
@{
Layout = "_RefinedLayout.cshtml";
}
@section DataTableScripts{
<div>It works </div>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
有关详细信息,请参阅MortenMeisler 的解决方法
推荐阅读
- php - 两种 PHP 缓存技术
- powershell - 将对象属性添加到 Powershell 中的另一个对象
- ios - MFMailComposeViewController 布局错误
- parameters - Wiremock 单个查询参数的多重匹配
- java - MongoDB Java 驱动程序不会连接到副本集或辅助服务器
- c# - 如何在c#中将二维码附加到促销图片
- c++ - 使用 Hoare 分区方案的快速排序算法返回原始未排序列表
- php - 无法在 laravel 5.4 中添加 spatie/laravel-sluggable 包
- cors - 为什么设置 XMLHttpRequest.withCredentials = true 允许 CORS 请求?
- java - 为什么 CompletableFuture 方法不返回 CompletionState