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

和自甴很熟 提交于 2019-12-24 03:36:05

问题


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!


回答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);
}


来源:https://stackoverflow.com/questions/13124218/asp-net-mvc-4-use-bundles-benefits-for-url-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!