首页 > 解决方案 > 如何在 cshtml 文件中调用外部 javascript 文件

问题描述

下面是我的 Javascript 文件。

复制.js

function CopyYourSheet() {

    var ifrm = document.createElement("iframe");
    ifrm.setAttribute("src", "https://docs.google.com/spreadsheets/d/1992ry0dpIjel_TQuB-W6fb2Nd7uST69AX_jY/edit#");
    ifrm.style.width = "10000px";
    ifrm.style.height = "2000px";
    document.body.appendChild(ifrm);
    }

下面是 CSHTML 文件

索引.cshtml

@{
    ViewData["Title"] = "Home Page";
}

    <div class="text-center">
        <h1 class="display-4">Welcome</h1>                    
        <button id="CopyYourSheet" onclick="CopyYourSheet()">Get your details</button>
    </div>

标签: javascriptasp.net-mvcrazor

解决方案


包含它的正确方法是将 Copy.js 捆绑到您的包中。

在 App_Start 文件夹下打开 BundleConfig

然后加

bundles.Add(new ScriptBundle("~/bundles/myjs").Include(
                        "~/Scripts/copy.js"));

然后像这样将它包含在您的主页视图中

@Scripts.Render("~/bundles/myjs")

如果您没有 App_Start 文件夹或者您不喜欢捆绑到 MVC 项目中,则将脚本包含在<head>您的 _Layout 局部视图的标签中。将它添加到结束标签的正上方</head>是最好的。

<script src="~/Scripts/copy.js"></script>

确保文件的路径正确。如果 js 文件位于主项目树中,您可能需要删除 src 路径中的 /Scripts/ 文件夹。~ 应该保留在路径的开头,以便在从不同环境运行代码时使其灵活。


推荐阅读