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
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.