Note this is written for Scripts but also works for Styles (just change those key words)
Building on @Johan's answer:
public static IHtmlString RenderBundle(this HtmlHelper htmlHelper, string path)
{
var context = new BundleContext(htmlHelper.ViewContext.HttpContext, BundleTable.Bundles, string.Empty);
var bundle = System.Web.Optimization.BundleTable.Bundles.GetBundleFor(path);
var html = System.Web.Optimization.Scripts.Render(path).ToString();
foreach (var item in bundle.EnumerateFiles(context))
{
if (!html.Contains(item.Name))
continue;
html = html.Replace(item.Name, item.Name + "?" + item.LastWriteTimeUtc.ToString("yyyyMMddHHmmss"));
}
return new HtmlString(html);
}
public static IHtmlString RenderStylesBundle(this HtmlHelper htmlHelper, string path)
{
var context = new BundleContext(htmlHelper.ViewContext.HttpContext, BundleTable.Bundles, string.Empty);
var bundle = System.Web.Optimization.BundleTable.Bundles.GetBundleFor(path);
var html = System.Web.Optimization.Styles.Render(path).ToString();
foreach (var item in bundle.EnumerateFiles(context))
{
if (!html.Contains(item.Name))
continue;
html = html.Replace(item.Name, item.Name + "?" + item.LastWriteTimeUtc.ToString("yyyyMMddHHmmss"));
}
return new HtmlString(html);
}
Usage:
@Html.RenderBundle("...")
@Html.RenderStylesBundle("...")
Replacing
@Scripts.Render("...")
@Styles.Render("...")
Benefits:
- Works for v1.0.0.0 of System.Web.Optimizations
- Works on multiple files in the bundle
- Gets the file modification date, rather than hashing, of each file, rather than a group
Also, when you need to quickly workaround Bundler:
public static MvcHtmlString ResolveUrl(this HtmlHelper htmlHelper, string url)
{
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var resolvedUrl = urlHelper.Content(url);
if (resolvedUrl.ToLower().EndsWith(".js") || resolvedUrl.ToLower().EndsWith(".css"))
{
var localPath = HostingEnvironment.MapPath(resolvedUrl);
var fileInfo = new FileInfo(localPath);
resolvedUrl += "?" + fileInfo.LastWriteTimeUtc.ToString("yyyyMMddHHmmss");
}
return MvcHtmlString.Create(resolvedUrl);
}
Usage:
<script type="text/javascript" src="@Html.ResolveUrl("~/Scripts/jquery-1.9.1.min.js")"></script>
Replacing:
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.9.1.min.js")"></script>
(Also replaces many other alternative lookups)