Using sections in Editor/Display templates

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

    This post really helped me so I thought I would post my implementation of the basic idea. I've introduced a helper function that can return script tags for use in the @Html.Resource function.

    I also added a simple static class so that I can use typed variables to identify a JS or CSS resource.

    public static class ResourceType
    {
        public const string Css = "css";
        public const string Js = "js";
    }
    
    public static class HtmlExtensions
    {
        public static IHtmlString Resource(this HtmlHelper htmlHelper, Func template, string Type)
        {
            if (htmlHelper.ViewContext.HttpContext.Items[Type] != null) ((List>)htmlHelper.ViewContext.HttpContext.Items[Type]).Add(template);
            else htmlHelper.ViewContext.HttpContext.Items[Type] = new List>() { template };
    
            return new HtmlString(String.Empty);
        }
    
        public static IHtmlString RenderResources(this HtmlHelper htmlHelper, string Type)
        {
            if (htmlHelper.ViewContext.HttpContext.Items[Type] != null)
            {
                List> resources = (List>)htmlHelper.ViewContext.HttpContext.Items[Type];
    
                foreach (var resource in resources)
                {
                    if (resource != null) htmlHelper.ViewContext.Writer.Write(resource(null));
                }
            }
    
            return new HtmlString(String.Empty);
        }
    
        public static Func ScriptTag(this HtmlHelper htmlHelper, string url)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            var script = new TagBuilder("script");
            script.Attributes["type"] = "text/javascript";
            script.Attributes["src"] = urlHelper.Content("~/" + url);
            return x => new HtmlString(script.ToString(TagRenderMode.Normal));
        }
    }
    

    And in use

    @Html.Resource(Html.ScriptTag("Areas/Admin/js/plugins/wysiwyg/jquery.wysiwyg.js"), ResourceType.Js)
    

    Thanks to @Darin Dimitrov who supplied the answer in my question here.

提交回复
热议问题