Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save huobazi/9074a9eb23ebbe0be13ad9e694e7942b to your computer and use it in GitHub Desktop.
Save huobazi/9074a9eb23ebbe0be13ad9e694e7942b to your computer and use it in GitHub Desktop.
Two C# extension methods for inlining script and style bundles into the HTML response using ASP.NET MVC and the System.Web.Optimization framework.
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
@Html.InlineStyles("~/some/path/to/a/bundle.css")
</head>
<body>
@RenderBody()
@Html.InlineScripts("~/some/path/to/a/bundle.js")
</body>
</html>
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
public static class HtmlHelperExtensions
{
public static IHtmlString InlineScripts(this HtmlHelper htmlHelper, string bundleVirtualPath)
{
return htmlHelper.InlineBundle(bundleVirtualPath, htmlTagName: "script");
}
public static IHtmlString InlineStyles(this HtmlHelper htmlHelper, string bundleVirtualPath)
{
return htmlHelper.InlineBundle(bundleVirtualPath, htmlTagName: "style");
}
private static IHtmlString InlineBundle(this HtmlHelper htmlHelper, string bundleVirtualPath, string htmlTagName)
{
string bundleContent = LoadBundleContent(htmlHelper.ViewContext.HttpContext, bundleVirtualPath);
string htmlTag = string.Format("<{0}>{1}</{0}>", htmlTagName, bundleContent);
return new HtmlString(htmlTag);
}
private static string LoadBundleContent(HttpContextBase httpContext, string bundleVirtualPath)
{
var bundleContext = new BundleContext(httpContext, BundleTable.Bundles, bundleVirtualPath);
var bundle = BundleTable.Bundles.Single(b => b.Path == bundleVirtualPath);
var bundleResponse = bundle.GenerateBundleResponse(bundleContext);
return bundleResponse.Content;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment