简体   繁体   中英

How do i call external javascript file in cshtml file

Below is my Javascript file.

Copy.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);
    }

Below is the CSHTML File

Index.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>

The right way to include it is through bundling the Copy.js into your bundle.

under App_Start folder open BundleConfig

Then add

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

then include it in your Home view like this

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

If you do not have an App_Start folder or you do not prefer to bundle in an MVC project, then include the script inside of the <head> tags of your _Layout partial view. Adding it right above the closing </head> tag would be best.

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

Be sure the path to the file is correct. You may need to remove the /Scripts/ folder in the src path, if the js file resides in your main project tree. The ~ should remain at the start of the path to make it flexible when the code is ran from different environments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM