23

I need to render some script in the head section of an ASP.NET MVC view. How can this be achieved?

In ASP.NET we had ContentPlaceHolders in Master. What is the MVC equivalent of implementing this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
StringBuilder
  • 1,619
  • 4
  • 32
  • 52

1 Answers1

47

You can use @section like this:

Master file:

@RenderSection("masterjs", required: false)

View file:

@section masterjs
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script> 
}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
user2031802
  • 744
  • 8
  • 7
  • 6
    Shouldn't this be otherway round? @RenderSection() in the master file(or in the _Layout.cshtml) and @section in the view file? – RasikaSam Jun 06 '14 at 01:46
  • The answer is correct. The RenderSection is where the code/script is inserted which is in the layout file. The section describes what script should be inserted for a specific page. That way each page can insert a different script file into the head of the page. – ChrisP Jun 06 '16 at 21:43
  • What does required false mean? – eaglei22 Jan 17 '17 at 14:58
  • "required: false" means the section is optional. If this is set to true you will get an error if it can't find the section it's looking for on your page – AndyWarby Jun 09 '22 at 06:51