Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
}
@dibugreen
Copy link

dibugreen commented Feb 21, 2021

thx for sharing sir..
any sample how it work in view using inline script, and how it's work . do we have to make dummy "~/some/path/to/a/bundle.js" to fill bunde.js automatically from inline script in view..
thank for advance and really sorry for my english

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment