I have downloaded a chat example from the Microsoft website. I have been following several tutorials but I have never seen the @section script{} before I have done scripts with
I'd just like to add another form of answer here, because it took me a combo of reading all three current answers and some experimenting before I understood it.
I copied some ajax code for a modal popup that was enclosed in @section scripts { }
and put it in a view. It worked fine, but I took away the section
bit, because it was encapsulated in html - which is normally fine;
My view before:
@Section scripts {
}
The rest of the page
How I normally include a one-off script on a view:
The rest of the page
By doing this, the script is rendered inside the html of the view itself and the popup stopped working. This is because the script accesses elements outside of that view - it needs site-wide access so to be able to stop using @section scripts
I would have to be put in the layout file.
But I only really want this script rendered when this view is being used. I don't want to put it in the _layout
file and have it loading on every single page.
Lucky me! At the bottom of a default _layout
file there's a line (I normally remove, to be honest):
@RenderSection("scripts", required: false)
So by enclosing my s in
@section scripts { }
on any view, it becomes part of the _layout
, and is loaded after all other content (it's right at the bottom of the layout page), but only when that particular view is used.
It basically allows a dynamic layout page which is very clever, I wonder if it's possible to do with stylesheets too.