Two C# extension methods for inlining script and style bundles into the HTML response using ASP.NET MVC and the System.Web.Optimization framework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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