Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

organizing custom javascripts in asp.net mvc 4

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.

I use Areas too, so that adds up the complexity. I was thinking about placing my scripts in the Script folder at the root of the application and then in a Custom sub-folder.

How would I then reference the scripts in my Views ? Should I use custom Bundles ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 appstartBundleConfig.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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...