Search code examples
asp.net-mvcperformancehead

MVC head components


I'm quite new to MVC. In my website I use a layout for all the views and I was wondering how could I add links to certain .css files.

What I mean is that if I add them in the _layout.cshtml, all HTML files will have that link although some of them don't need it, which could lead to performance issues??

How could I do this? Thanks!


Solution

  • Layout page works like a master page. You can define a section in the partial view and then render it in the layout page:

    Define a section named (Styles) in the view that needs (yourView_style.css) file to be rendered:

    @section Styles {
        <link href="@Url.Content("~/Styles/yourView_style.css")" rel="stylesheet" type="text/css" />
    }
    

    In (_layout.cshtml) render the (Styles) section:

    <head>
        <link href="@Url.Content("~/Styles/main.css")" rel="stylesheet" type="text/css" />
        @RenderSection("Styles", false)
    </head>