Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc4 bundling strongly typed bundles

So MVC 4 introduces script and style bundling. Which allows for this:

public static void RegisterBundles(BundleCollection bundles)
    {
    bundles.Add(new ScriptBundle("~/bundles/mobile").Include(
                    "~/Scripts/jquery.mobile-*"));

then used in a razor view like this:

@Scripts.Render("~/bundles/mobile")

My question is why do I have to type "~/bundles/mobile"? Is there a way get intellisence to have a strongly typed object to pick up on? Otherwise I have to go look it up to make sure I call it the same thing.

I would like to do something like this: (I know this won't compile this way, it's just an example)

public static void RegisterBundles(BundleCollection bundles)
    {
    Bundle mobile = new Bundle("mobile");
    mobile.AddFile("w/e")
    bundles.Add(mobile);

//in page:
 @Scripts.Render(BundleConfig.mobile)

or something to that affect.

Edit: the answer so simple. As @Hao Kung points out @Styles.Render simply takes a url string path. I created a class to hold the pathes.

public class bundles
{
    #region Javascript
    public static string scripts = "~/bundles/scripts";
    ...
    #endregion

    #region CSS

    public static string css = "~/Content/css";
    public static string jqueryUi = "~/Content/themes/base/css";
    ...
    #endregion
}

in any page then you simply do

@Styles.Render(bundles.jqueryUi)

there you have it. A little extra effort on your part, but at least it's strongly typed now.

like image 406
Eonasdan Avatar asked Nov 04 '22 21:11

Eonasdan


1 Answers

The Render Scripts/Styles Render helpers are not limited to rendering references to bundles, they resolve any urls, so the only way for the helper to detect that you mean to reference a bundle, is by passing in the virtual path of the bundle.

like image 105
Hao Kung Avatar answered Nov 08 '22 10:11

Hao Kung