简体   繁体   中英

MVC - is there a nice way to bundle controls with their respective javascript?

I'm pretty new to MVC and I can't decide on the best way to store cshtml files and their respective javascript code. Some JS code in my project needs to run globally, but most of it is entirely tied to specic views or partial views.

If I put the javascript in the views, I get a mess of inline uncacheable javascript, if I put it in one central file, I lose modularity.

I heard that in MVC4 there are going to be minification features, is there something I can do with MVC3 that will allow me to choose in the Views which javascripts to include and then group them and minify them automatically? (maybe even in groups?)

Cassette it's essentially the same thing as the upcoming MVC4 bundles.

In your view page, you can reference scripts and stylesheets using Cassette's Bundles helper class.

@{
    Bundles.Reference("Scripts/jquery.js");
    Bundles.Reference("Scripts/page.js");
    Bundles.Reference("Styles/page.css");
}
<!DOCTYPE html>
    <html>
...

In addition, Cassette has native support for Less and CoffeScript . It has also support for HTML Templates, if you are interested in client side MVC frameworks like Knockout.js or Backbone.js .

Still you have to choose how to group your content. As the official documentation is suggesting, probably the best choice is to treat bundles as units of deployment .

Keep in mind that a bundle is a . If any asset in a bundle changes, then the entire bundle has to be downloaded again by web browsers. .

You can put the javascript in separate files, for each view. Then in the _Layout.cshtml enter a @RenderSection to the head:

<head>
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
    @RenderSection("head",false)
</head>

Then in each view, you can put a section that will be rendered into the header:

@section head{
    <script src="@Url.Content("~/ViewScripts/Order/New.js")" type="text/javascript"></script>
}

@Anders approach is good if you require the scripts to be in the head tag. But I find that most times it is not required if it is page specific JavaScript. You can put your script tags that reference your script files wherever they are required in the View. Automatically bundling and minification will be supported in ASP.NET 4.5 . Until that time you can integrate yuicompressor into Visual Studio.

It is not a best practice to use script in partials (in my point of view)

is suggest you to write partial specific script to separate js and bind events on page load or if partial was loaded via ajax then on success event.

then you can be sure that events are not bound multiple times and view is just a view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM