ASP.NET Mvc 4 Use bundle's benefits for Url.Content
Asked Answered
M

1

2

Is there any way I can do this?

Some of the benefits of bundling are:

  • Minimization
  • Gzip compression
  • The request has a token parameter for handling files versiones (cache).

In my site I use a lot of bundles, but in some pages I only have 1 script and I don't think I should create a bundle only for 1 script. Is there any way I can use this three benefits with Url.Content method.

My utopic solution would be to set up something (maybe in the web.config) and whenever Url.Content is called it adds this functionality. Using it in either of this ways:

<script type="text/javascript" src="@Url.Content("~/Scripts/...")"></script>
<script type="text/javascript" src="~/Scripts/..."></script>

(The second one is because I'm using Razor 2)

If that is not possible I can make an extension method to UrlHelper to add this functionality.

Thanks!

Marchall answered 29/10, 2012 at 15:2 Comment(0)
H
1

There's nothing really wrong with creating a bundle with one file to get the benefits of minification and versioning. You would have to use the Scripts.Render helper as well, there's no support for this in the UrlHelper currently, but as you mentioned already you could write an extension method to call into the Scripts helper.

Update (by OP)

Here are my extension method for anyone who want to use it:

public static IHtmlString DynamicScriptsBundle(this HtmlHelper htmlHelper, string nombre, params string[] urls)
{
    string path = string.Format("~/{0}", nombre);
    if (BundleTable.Bundles.GetBundleFor(path) == null)
        BundleTable.Bundles.Add(new ScriptBundle(path).Include(urls));
    return Scripts.Render(path);
}

public static IHtmlString DynamicStylesBundle(this HtmlHelper htmlHelper, string nombre, params string[] urls)
{
    string path = string.Format("~/{0}", nombre);
    if (BundleTable.Bundles.GetBundleFor(path) == null)
        BundleTable.Bundles.Add(new StyleBundle(path).Include(urls));
    return Styles.Render(path);
}
Hammerskjold answered 30/10, 2012 at 17:5 Comment(2)
I already have my HtmlHelper to create (if necessary) and use a bundle from the View. I'm still not very convinced of creating the bundle for 1 file. Is there no other way?Marchall
This is a good solution for using Bundles.Add() from within .aspx files. I recently converted a web app to use bundling and considered using this approach, but it would have meant lots of manual edits to replace <script> tags with <%= DynamicScriptsBundle(...)%>. I was hoping to simply wrap <script> tags in a custom server control, but my solution ended up being a bit more involved and required manual edits anyway. Oh well. If curious, see my alternate solution here: #17438300Wingate

© 2022 - 2024 — McMap. All rights reserved.