why I can use css file in pages but can not use js file?

mc 5,426 Reputation points
2023-02-12T02:27:53.0733333+00:00

User's image

I can add Index.cshtml.css and use it

but I can not add Index.cshtml.js why?

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-02-12T14:20:07.7066667+00:00

    I can add Index.cshtml.css and use it but I can not add Index.cshtml.js why?

    CSS files must be added in the <head> tag which is located in the layout.cshtml. While it has always been possible to inject CSS specific to a page/view, this is code you must write and maintain. The new CSS Isolation feature simply lets you add CSS at a page level.

    CSS Isolation In Razor Pages

    A JavaScript file can be referenced from any location within the HTML. The convention is referencing JavaScript at the end of the HTML which is handled using the following convention.

    @Section scripts {
    }
    
    
    0 comments No comments

  2. Xinran Shen - MSFT 2,091 Reputation points
    2023-02-13T01:42:25.3066667+00:00

    Hi @打玻璃.

    The way you add CSS file is called CSS Isolation, It is a new feature in .Net 6. But we don't use this way to add js file. A common way is to add JS file into wwwroot folder.

    For Example, If you want to use JavaScript file called Index.js in your page, First you need to add this file into js folder under wwwroot, Then add a reference to this file in your page:

    <script src="~/js/Index.js"></script>
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Xinran Shen

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.