Using sections in Editor/Display templates

后端 未结 8 824
爱一瞬间的悲伤
爱一瞬间的悲伤 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:46

    You could proceed with a conjunction of two helpers:

    public static class HtmlExtensions
    {
        public static MvcHtmlString Script(this HtmlHelper htmlHelper, Func<object, HelperResult> template)
        {
            htmlHelper.ViewContext.HttpContext.Items["_script_" + Guid.NewGuid()] = template;
            return MvcHtmlString.Empty;
        }
    
        public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
        {
            foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
            {
                if (key.ToString().StartsWith("_script_"))
                {
                    var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
                    if (template != null)
                    {
                        htmlHelper.ViewContext.Writer.Write(template(null));
                    }
                }
            }
            return MvcHtmlString.Empty;
        }
    }
    

    and then in your _Layout.cshtml:

    <body>
    ...
    @Html.RenderScripts()
    </body>
    

    and somewhere in some template:

    @Html.Script(
        @<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
    )
    
    0 讨论(0)
  • 2020-11-22 17:47

    @Darin Dimitrov and @eth0 answers to use with bundle extention usage :

    @Html.Resources(a => new HelperResult(b => b.Write( System.Web.Optimization.Scripts.Render("~/Content/js/formBundle").ToString())), "jsTop")
    
    0 讨论(0)
提交回复
热议问题