1

I'm sure this question must have been asked and answered somewhere on StackOverflow, but I've searched and searched and it's eluding me. I'd be very grateful of any assistance the community might provide.

I have a form with which I'm quite happy, but I'd like to improve it with a touch of JavaScript. The JS isn't relevant to any other page of my app, so I don't want to add it to my _Layout page.

Within the head element of my _Layout.cshtml page I have:

@RenderSection("head", required: false)

So, I need a line of code for my page (let's call it page.cshtml) that will add a block of JS (including script tags) into the head section of my eventual HTML. Essentially, I need to send a block of text to the RenderSection object, I think. Could someone tell me the correct syntax to put into my page.cshtml?

1 Answers1

1

Why you need to add scripts specially to head section? MVC default _Layout page has @RenderSection("scripts", required: false) section. So if you need to load scripts on your View page.cshtml (That uses _Layout) you should place a code:

@section scripts {
    <script type="text/javascript">
       //your script
    </script>
}

When Razor render your page it will add this script to section.

Anyway if you want to add sctipt to this particulad head section it could be done same way:

@section head {
    //other code that should be in head
    <script type="text/javascript">
       //your script
    </script>
}
teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • Thanks teo. I knew it was something like that but for some odd reason I was putting it in my code block and was a bit confused that I got no syntax highlighting. So now of course it can just be .... well, pretty much anywhere really. As for why I put JS specifically in the head - sorry, but it's just where I've put JS functions 99% of the time! Your question has got me thinking about why I do that though. – Stuart Newbridge Mar 03 '16 at 14:13