9

Below is my Problem :

enter image description here

GlobalJs.js is my custome JavaScript file and has only one line code alert(1).

enter image description here

But I am unable to add its reference in _Layout.cshtml.

enter image description here

src="../JavaScript/GlobalJs.js" or src="~/JavaScript/GlobalJs.js" none is working for me. What is the problem actually? Please anyone help me. Am I missing something?

Thanks in advance.

3 Answers 3

17

In ASP.NET Core, static files such as javacript, css etc are serve to web browser from wwwroot folder.

Hence, you need to move these files into wwwroot folder and then reference files in _Layout.cshtml using <script src="~/JavaScript/GlobalJs.js"></script>

For more information, please refer this article

Sign up to request clarification or add additional context in comments.

1 Comment

Out of all the answers on SO explaining this, this answer is the easiest to understand :-) +1
3

In ASP.NET Core, Static files, such as HTML, CSS, image, and JavaScript, are assets that serve from wwwroot folder to web browser.

Hence, you need to move these files into wwwroot folder and then reference files in _Layout.cshtml using <script src="~/JavaScript/GlobalJs.js"></script>

Note: In order for static files to be served, you must configure the Middleware to add static files to the pipeline. The static file middleware can be configured by adding a dependency on the Microsoft.AspNetCore.StaticFiles package to your project and then calling the UseStaticFiles extension method from Startup.Configure

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}

1 Comment

this answer seems to duplicate the accepted one, or the other way around? :)
0

I came here with the same problem but my solution was to double check that the javascript file was copy to the solution. Easy to forget this configuration, right click on the file and select properties:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.