2

There are some views that I create which use the _layout partial view, but I don't want to include every single css or script bundle. What is the best way to include the script or css file in the view?

<head>
 <link href="Content/style.css" .../>
 <script src="Scripts/myscript.js" ...></script>
</head>

How can I get the view to render something similar to this? There is no head tag in a View that uses a partial view.

JoshYates1980
  • 3,476
  • 2
  • 36
  • 57
  • **primarily opinion-based:** _Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise._ – emerson.marini Jul 25 '14 at 14:57
  • You can use partial sections and use this approach: http://stackoverflow.com/questions/13764936/how-to-render-a-section-in-a-partial-view-in-mvc3/13765578#13765578 – Mario Levrero Jul 25 '14 at 14:58
  • @MelanciaUK Would you care help me here, please? I'm reading the question, I follow the answer, it helped me with my precise uncertainty in a very quick way. How is it too broad or opinion based, please? It's a very good question that **should** be asked because it leads to a better structure of code base. – Konrad Viltersten Jan 17 '16 at 14:21

2 Answers2

5

With Razor layouts, you can use Sections to define what scripts/CSS files you wish to load in your master layout file in your partials rather than in your master.

You can read more about Sections here, on Scott Guthrie's blog

In your shared _Layout.cshtml file, you could add

<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    @RenderSection("css")
    @RenderSection("scripts")
</head>

And in a particular View...

<div> lol some content </div>
@section css {
   <link rel="stylesheet" type="text/css" href="homeTheme.css">
}
@section scripts {
   <script src="../../Scripts/home.js"></script>
}
  • exactly what I needed. I have some html5 video.js and video.css I didn't want to include in my _layout page used throughout my application. And I didn't want to make a new partial view. Thanks! – JoshYates1980 Jul 25 '14 at 15:12
  • wait...is it @section css? I get a runtime error "The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml" – JoshYates1980 Jul 25 '14 at 15:32
  • 1
    @JoshYates1980 you defined a section in the view, but it is not rendered in the layout. For every `@section` you define in a view, it must correspond to a RenderLayout call in the shared layout file. Check the exception details, check your code. –  Jul 25 '14 at 15:43
0

You can load the css & scripts files common to the project in the Master page. And, only load the ones that are needed in the partial view by adding a link or script tag at the end of the rest of the markup in the partial view.

Vikram Deshmukh
  • 12,304
  • 4
  • 36
  • 38