将多个 .js 包含移动到一个包含中的正确方法?

Proper way to move multiple .js includes into one include?

我有 2 个具有类似如下结构的 Razor .cshtml 文件:

<script type="text/javascript" src='@Url.Content("~/Scripts/jqwidgets/jqxcore.js")'></script>
<script type="text/javascript" src='@Url.Content("~/Scripts/jqwidgets/jqxdata.js")'></script>
<script type="text/javascript" src='@Url.Content("~/Scripts/jqwidgets/jqxbuttons.js")'></script>
...

<More header stuff (different in both files)>

<script language="javascript" type="text/javascript">
   function commonFunctionForJqWidgets() {
      ...
      callSomethingFromJqWidgetsLibrary();
      ...
   }
</script>

我正在为这 2 个文件编写通用代码,并希望将通用代码放在另一个 .js(或 .cshtml)文件中,而不是在两个地方都复制它。但是,公共代码需要包含一些 jqwidgets include,因为它会为其调用库函数。

处理这个问题的正确方法是什么?我是否应该简单地添加一个新的 .cshtml 文件,将所有包含文件移到其中,然后在其中定义我的常用函数?

通常当您有公共 UI 代码时,您可以将其放在一个局部视图中,该视图可以根据需要包含在其他视图中。但在你的情况下,它更像是一堆 javascript 你想要的文件在多个文件中。因此,您可以创建一个 script bundle,它将包含所有这些脚本,并根据需要在您的页面中使用它们。

public class BundleConfig
{

    public static void RegisterBundles(BundleCollection bundles)
    {
        // Your existing bundles here

        bundles.Add(new ScriptBundle("~/bundles/jQxWidgets")
                  .Include(
                  "~/Scripts/jqwidgets/jqxcore.js",
                  "~/Scripts/jqwidgets/jqxdata.js",
                  "~/Scripts/jqwidgets/jqxbuttons.js",
                  "~/Scripts/SomeOtherCustomJsfileRelatedtojQxWidgets.js"));
    }
}

在您的特定视图中,您可以将其包含在 Scripts 部分中。

@section Scripts
{
  @Scripts.Render("~/bundles/jQxWidgets")
}

如果您的常用内容不仅仅是脚本,请创建一个局部视图并在其中包含常用内容,并根据需要将此局部视图包含在其他视图中.

在您的 ~/Views/Shared 文件夹中创建一个名为 CommonGrid.cshtml 的局部视图

<h2>Common header for both the pages </h2>
@section Scripts
{
  @Scripts.Render("~/bundles/jQxWidgets")
}

而在你的其他观点中

UserList.cshtml

<h1>Users</h1>
@Html.Partial("CommonGrid")

ProductList.cshtml

<h1>Products</h1>
@Html.Partial("CommonGrid")

您还可以将您的 CommonGrid 强类型化为视图模型,并在您页面特定的这种类型(CommonGrid 的视图模型)的视图模型中创建一个 属性 并将其传递到 Html.Partial 方法中.