首页 > 解决方案 > 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?

标签: asp.netasp.net-core

解决方案


只需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的并将Layoutof设置ViewComponentRefinedLayout

@{
    Layout = "_RefinedLayout.cshtml";
}

@section DataTableScripts{
    <div>It works </div>
    <script src="~/js/JQuery/jquery.dataTables.js"></script>
} 

有关详细信息,请参阅MortenMeisler 的解决方法


推荐阅读