How does MVC4 optimization allow partial view scripts?

后端 未结 1 1957
面向向阳花
面向向阳花 2021-02-15 06:11

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:56

    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__";
    
        /// 
        /// Call this method from your partials and register your script bundle.
        /// 
        public static void Register(this HtmlHelper htmlHelper, string scriptBundleName)
        {
            //using a HashSet to avoid duplicate scripts.
            HashSet set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet;
            if (set == null)
            {
                set = new HashSet();
                htmlHelper.ViewContext.HttpContext.Items[Key] = set;
            }
    
            if (!set.Contains(scriptBundleName))
                set.Add(scriptBundleName);
        }
    
        /// 
        /// In the bottom of your HTML document, most likely in the Layout file call this method.
        /// 
        public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
        {
            HashSet set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet;
            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()
    
    

    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)
提交回复
热议问题