无法在ViewComponent中加载脚本 [英] Cannot load script in ViewComponent
问题描述
我创建了一个 ViewComponent
,其中显示了一个 Table
,该表需要一些插件才能启用特定功能.在 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>
}
不幸的是,我发现 ViewComponent
无法加载 @section
.
unfortunately I discovered that a ViewComponent
cannot load a @section
.
因此,我尝试将脚本直接包含在 ViewComponent
中,但是问题在于脚本是在 JQuery
之前加载的,而 _Layout内部加载的
,具体是:
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>
布局
<script src="~/js/jquery.min.js"></script>
所以在这种情况下,我会得到:
so in this case I'll get:
未定义jQuery
jQuery is not defined
如何处理这种情况?
推荐答案
只需为ViewComponent设置 Layout
即可.
Simply set the Layout
for your ViewComponent .
@{
Layout = "/Views/Shared/_Layout.cshtml";
}
@section DataTableScripts{
<div>It works </div>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
以下是有效的屏幕截图:
Here's the screenshot that works :
这种方法似乎不是实现此目的的好方法.正如 @Kirk Larkin 所说,这将使 Layout
呈现两次.另一个补丁是编写一个新的 RefinedLayout.cshtml
并将 ViewComponent
的 Layout
设置为 RefinedLayout
:>
This approach does not seems a good way to do that . As @Kirk Larkin says , this will make the Layout
render twice . Another patch is to write a new RefinedLayout.cshtml
and set the Layout
of ViewComponent
as the RefinedLayout
:
@{
Layout = "_RefinedLayout.cshtml";
}
@section DataTableScripts{
<div>It works </div>
<script src="~/js/JQuery/jquery.dataTables.js"></script>
}
有关更多信息,请参见 MortenMeisler的解决方法
For more information , refer workaround by MortenMeisler
这篇关于无法在ViewComponent中加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!