What is @section scripts and what it is used for

前端 未结 4 1301
不知归路
不知归路 2021-01-31 02:21

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

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 03:00

    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 }

    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

提交回复
热议问题