Using sections in Editor/Display templates

后端 未结 8 955
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 17:15

I want to keep all of my JavaScript code in one section; just before the closing body tag in my master layout page and just wondering the best to go about it, M

8条回答
  •  无人及你
    2020-11-22 17:33

    Install the Forloop.HtmlHelpers nuget package - it adds some helpers for managing scripts in partial views and editor templates.

    Somewhere in your layout, you need to call

    @Html.RenderScripts()
    

    This will be where any script files and script blocks will be outputted in the page so I would recommend putting it after your main scripts in the layout and after a scripts section (if you have one).

    If you're using The Web Optimization Framework with bundling, you can use the overload

    @Html.RenderScripts(Scripts.Render)
    

    so that this method is used for writing out script files.

    Now, anytime you want to add script files or blocks in a view, partial view or template, simply use

    @using (Html.BeginScriptContext())
    {
      Html.AddScriptFile("~/Scripts/jquery.validate.js");
      Html.AddScriptBlock(
        @
      );
    }
    

    The helpers ensure that only one script file reference is rendered if added multiple times and it also ensures that script files are rendered out in an expected order i.e.

    1. Layout
    2. Partials and Templates (in the order in which they appear in the view, top to bottom)

提交回复
热议问题