organizing custom javascripts in asp.net mvc 4

后端 未结 2 949
别跟我提以往
别跟我提以往 2020-12-15 20:25

I\'m new to mvc 4 and I\'m wondering where I should put my custom javascript files. By \'custom\', I mean scripts that are only used in specific Views or PartialViews.

相关标签:
2条回答
  • 2020-12-15 20:59

    You could organize your scripts in the Scripts folder:

    • ~/Scripts/Home/foobar.js
    • ~/Scripts/Admin/baz.js
    • ...

    Should I use custom Bundles ?

    Sure, you could bundle the scripts that always go together.

    0 讨论(0)
  • 2020-12-15 21:00

    i think that adding your scripts to a custom folder in your scripts folder is the way to go. you can create a new bundle in the appstart\BundleConfig.cs file as follows:

    bundles.Add(new ScriptBundle("~/bundles/custom").Include(
                       "~/Scripts/Custom/myCustom.js",
                       "~/Scripts/Custom/myCustom2.js"));
    

    and than add the bundle to your view like this:

    @section scripts{
    
     @Scripts.Render("~/bundles/custom")
    
    }
    

    this will be rendered at the @RenderSection("scripts", required: false) line on your layout file.

    OR
    To call only one specific script for your view you can do:

    @section scripts{
    <script src="~/Scripts/Custom/myCustom.js"></script>
    }
    

    note: you can drag the script file from the solution explorer into the section. you don't have to write the entire path.
    EDIT - seems important so i copied this from my last comment:
    in order to use minification you need to add your script to the bundle table and either add BundleTable.EnableOptimizations = true; to the BundleConfig file or set <compilation debug="false" in your web.config file.

    0 讨论(0)
提交回复
热议问题