Reputation: 79
I am using System.Web.Optimization to bundle the css and script.But now I want to render css and scripts inline instead of refer to a single file.
I am trying to create an extension method for System.Web.Optimization.Render() but I am not able to provide parameter as HttpContextBase for the method GenerateBundleResponse()
Following is my code with Error
public static class OptimizationStylesExtention
{
private static string GetBundleContent(HttpContextBase httpContextBase,
string bundleVirtualPath)
{
return BundleTable.Bundles
.Single(b => b.Path == bundleVirtualPath)
.GenerateBundleResponse(new BundleContext(httpContextBase,
BundleTable.Bundles, bundleVirtualPath)).Content;
}
public static IHtmlString RenderInline(this HtmlString str, params string[]
bundleVirtualPath)
{
StringBuilder bundleContent = new StringBuilder();
foreach (var virtualPath in bundleVirtualPath)
{
bundleContent.Append(BundleTable.Bundles.Single(b => b.Path == virtualPath)
.GenerateBundleResponse(new BundleContext(str, BundleTable.Bundles, virtualPath)));
}
return new HtmlString(string.Format("{<style>{0}</style>}", bundleContent.ToString()));
}
}
Upvotes: 2
Views: 790
Reputation: 2138
Hello you can do using GenerateBundleResponse Metho. Which is the method of BundleResponse class.
Here is the code
using System.Web.Optimization;
/// <summary>
/// This is the extension for the bundle.
/// Which is used when we want to use inline css with style tag
/// </summary>
public static class BundleExtensions
{
/// <summary>
/// Returns inline css with style tag
/// </summary>
/// <param name="VirtualPath">Accepts Virtual Path</param>
/// <returns>string as inline css</returns>
public static string InlineStyle(string VirtualPath)
{
var CSSBundle = BundleTable.Bundles.GetBundleFor(VirtualPath);
var CSS = CSSBundle.GenerateBundleResponse(new BundleContext(new System.Web.HttpContextWrapper(System.Web.HttpContext.Current), BundleTable.Bundles, string.Empty)).Content;
return string.Format("<style type='text/css'>{0}</style>",CSS);
}
/// <summary>
/// Returns inline script with script tag
/// </summary>
/// <param name="VirtualPath">Accepts Virtual Path</param>
/// <returns>string as inline script</returns>
public static string InlineScript(string VirtualPath)
{
var JSBundle = BundleTable.Bundles.GetBundleFor(VirtualPath);
var JS = JSBundle.GenerateBundleResponse(new BundleContext(new System.Web.HttpContextWrapper(System.Web.HttpContext.Current), BundleTable.Bundles, string.Empty)).Content;
return string.Format("<script type='text/javascript'>{0}</script>", JS);
}
}
And In your ASP.NET Page, You can call that method as follows
<%=BundleExtensions.InlineStyle("~/css/new_home_page") %>
Thank You :)
Upvotes: 2