How to Properly Reference a JavaScript File in an ASP.NET Project?

前端 未结 4 849
醉梦人生
醉梦人生 2021-01-02 22:27

I have some pages that reference javascript files.

The application exists locally in a Virtual Directory, i.e. http://localhost/MyVirtualDirectory/MyPage.aspx

<
相关标签:
4条回答
  • 2021-01-02 22:31

    Another way in MVC5:

    1) in the layout html View file, place RenderSection in the place you need the script to be:

    <html><body>
    @RenderSection("scripts1", required: false)
    </body></html>
    

    note that you can change the "Scripts1" to be whatever name you like.

    2) in your view html file, just call the "scripts1", doesn't matter where, with your path and js file name:

    @Scripts1.Render("~/Scripts/MyScript.js")
    

    3) make sure the MyScript js file is in the Scripts Folder of your project.

    That's it.

    0 讨论(0)
  • 2021-01-02 22:35

    Use ResolveUrl("~/")

    <script src="<%=ResolveUrl("~/scripts/myscript.js") %>" type="text/javascript"></script>
    

    ~/ will get to you the root of your application, virtual or otherwise

    0 讨论(0)
  • 2021-01-02 22:50

    Previous answers seem to assume that the Scripts directory always exists as a subdirectory of your application root. If that assumption is correct, and if the page is also at the root, then both of your earlier tags can be simply:

    <script src="Scripts/MyScript.js" type="text/javascript"></script>
    

    But my read of your second example is that Scripts isn't always a subdirectory of your application root (because the ../ at the beginning moves up a level, so Scripts would be a peer of your application root). That said, you did say the second example didn't work. :-) But if that's really the case, I'd strongly recommend adjusting one environment or the other so that the relative paths agree, and then always using relative paths as above.

    The only reason for using ResolveUrl as far as I know would be if the pages in the application are in a folder structure and the tag may appear in a page at the root or in a page in a "subdirectory". If so, you can use ResolveUrl in both cases so you have an anchor point. I never author things that way, I always ensure I know where the page will be in the hierarchy (if there needs to be a hierarchy) and use an appropriate relative path for the current document.

    0 讨论(0)
  • 2021-01-02 22:56

    You can use the HttpRuntime.AppDomainAppVirtualPath property to get the virtual path (if any) for your app and use that to fix up the javascript paths (using <%= ... %> in the <script> tags etc.)

    You can further add a global javascript variable in your master page that exposes that value as well, so that any scripts that need to know the actual app root can access it that way.

    0 讨论(0)
提交回复
热议问题