How does MVC4 optimization allow partial view scripts?

后端 未结 1 2067
醉话见心
醉话见心 2021-02-15 06:09

One problem with partial views and MVC, is that if your reusable partial view requires certain javascript, there was no way to include it and have it loaded at the bottom of the

相关标签:
1条回答
  • 2021-02-15 06:47

    One thing you can do is create some HtmlHelper extension methods like the following:

    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Optimization;
    
    public static class ScriptBundleManager
    {
        private const string Key = "__ScriptBundleManager__";
    
        /// <summary>
        /// Call this method from your partials and register your script bundle.
        /// </summary>
        public static void Register(this HtmlHelper htmlHelper, string scriptBundleName)
        {
            //using a HashSet to avoid duplicate scripts.
            HashSet<string> set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;
            if (set == null)
            {
                set = new HashSet<string>();
                htmlHelper.ViewContext.HttpContext.Items[Key] = set;
            }
    
            if (!set.Contains(scriptBundleName))
                set.Add(scriptBundleName);
        }
    
        /// <summary>
        /// In the bottom of your HTML document, most likely in the Layout file call this method.
        /// </summary>
        public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
        {
            HashSet<string> set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;
            if (set != null)
                return Scripts.Render(set.ToArray());
            return MvcHtmlString.Empty;
        }
    }
    

    From your partials you would use it like this:

    @{Html.Register("~/bundles/script1.js");}
    

    And in your Layout file:

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

    Since your partials run before the end of the layout file all the script bundles will be registered and they will be safely rendered.

    0 讨论(0)
提交回复
热议问题