Skip to content

Instantly share code, notes, and snippets.

@ChrisMBarr
Created April 18, 2013 03:52
Show Gist options
  • Save ChrisMBarr/5409971 to your computer and use it in GitHub Desktop.
Save ChrisMBarr/5409971 to your computer and use it in GitHub Desktop.
Easy Bundles for .NET MVC4 - Blog post with explanation here: http://chris-barr.com/2013/04/easy-bundles-for-net-mvc4/
using System.Linq;
using System.Web.Optimization;
namespace System.Web.Mvc
{
public static class HtmlHelperExtensions
{
public static IHtmlString Script(this HtmlHelper helper, params string[] urls)
{
var bundleDirectory = "~/Scripts/bundles/" + MakeBundleName(".js", urls);
var thisBundle = new ScriptBundle(bundleDirectory).Include(urls);
BundleTable.Bundles.Add(thisBundle);
return Scripts.Render(bundleDirectory);
}
public static IHtmlString Style(this HtmlHelper helper, params string[] urls)
{
var bundleDirectory = "~/Styles/bundles/" + MakeBundleName(".css", urls);
var thisBundle = new StyleBundle(bundleDirectory).Include(urls);
BundleTable.Bundles.Add(thisBundle);
return Styles.Render(bundleDirectory);
}
private static string MakeBundleName(string type, params string[] urls)
{
var bundleSections = new List<string>();
foreach (var item in urls)
{
bundleSections.Add(item.Replace("~/", "").Replace("/", ".").Replace(type, ""));
}
return string.Join("+", bundleSections.ToArray());
}
}
}
//Syntax usage example
@Html.Style("~/Styles/someFile.css")
@Html.Script("~/Scripts/foo.js", "~/Scripts/bar.js")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment