Populate a Razor Section From a Partial

前端 未结 12 1508
不知归路
不知归路 2020-11-27 11:23

My main motivation for trying to do this is to get Javascript that is only required by a partial at the bottom of the page with the rest of the Javascript and not in the mid

12条回答
  •  暖寄归人
    2020-11-27 12:02

    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)

提交回复
热议问题