-1

Suppose I have a view called Login.cshtml, which I need to load these:

<link href="~/css/particle.css" rel="stylesheet" />
<script src="~/js/particle-js/particles.min.js"></script>
<script src="~/js/particle-js/app.js"></script>

In my application I have also _Layout.cshtml which contains the basic script to load for each, page. How can I load the script and css above in the when the user access to Login.cshtml view, as happen in _Layout.cshtml?

What I learned is the existence of @section, but I don't if is the best practive to do this, someone could suggest me how to do it properly?

Thanks in advance.

Charanoglu
  • 1,229
  • 2
  • 11
  • 30

1 Answers1

1

Section seems to be the appropriate solution for this use case.

So you will use the RenderSection method in your layout cshtml file. For example, if you want to include some static resources inside the head section of the document, you will create a new section in the head element of your layout

<head>
      @RenderSection("PageCss",required:false)
</head>
<body>
    <div>
       @RenderBody()
       @RenderSection("scripts", required: false)
    </div>
</body>

and in your view(Login.cshtml), you will add the static resources through this specific section.

@section PageCss
{
   <link href="~/css/particle.css" rel="stylesheet" />
   <script src="~/js/particle-js/particles.min.js"></script>
   <script src="~/js/particle-js/app.js"></script>    
}
@section PageCss
{
   <script src="~/js/anotherSciptWhichDoesNotBlockRendering.js"></script>
}

When razor executes the code, it will render the correct html.

You may create more than one section and use it as needed.

Consider using the async and defer attributes on script tag as appropriate to prevent render blocking script download/execution behavior.

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • 1
    +1, although it is best practice to load javascript at the bottom of the page, so it would probably be better to include two sections: 1 at the top for CSS and 1 at the bottom for JS. – Dave Smash Aug 30 '18 at 20:50