简体   繁体   中英

Managing js and css files in ASP.NET MVC

I am fairly new to ASP.NET MVC 4 and was wondering what is the ASP.NET way of including css and js files.

Background

In my PHP projects, I usually have arrays for CSS and JS file names that live in the controller. These arrays are passed in the master-template where a function loops through and generates the html tags for each item and auto-versions them at this point as well. The CSS resides in the <head> while the JS resides right before the </body> tag.

Things I am aware of

  1. The BundleConfig (However, I am strictly concerned with page-specific css/js not global ones)
  2. Creating some static function in a class that is passed in a list of files to generate the script and link tags accordingly

Question

How should I manage to include (and possibly auto-version and minify like BundleConfig) page specific js and css files from the view (or even the controller).?

One option is to use @RenderSection within you layout page to achieve this. In the layout page you include the files and/or bundles common to all pages using the layout and use @RenderSection to specify place holders where page specific files will be included (note the 2nd parameter = false makes it optional)

The layout page

<!DOCTYPE html>
<html>
  <head>
    <title>@ViewBag.Title</title>
    <link href="~/Content/Common.css" rel="stylesheet" /> // Common .css files here
    @RenderSection("styles", false) // Place holder for optional page specific .css files
    @Scripts.Render("~/bundles/modernizr")
  </head>
  <body>
    <div id="content">
      @RenderBody()
    </div>
    @Scripts.Render("~/bundles/jquery") // Common .js files or bundles
    @RenderSection("scripts", required: false) // Place holder for optional page specific .js files or bundles 
  </body>
</html>

Then in the page, define the sections for the page specific bundles and/or files

@model ....
// Page specific html
@section styles {
  <link href="~/Content/page-specific-stylesheet.css" rel="stylesheet" />
}
@section Scripts {
  @Scripts.Render("~/bundles/page-specific-bundle")
  <script src="~/Scripts/page-specific-file.js"></script>
  <script type="text/javascript">
    // page specific script
  </script>

}

There is no reason you cant create bundles for page specific files even if its only one file. The advantage is that for your production environment, the files will be automatically minified (unless you already have a file in the same folder appended with .min.js). By default the bundle is cached in the browser (for 12 months I think) and if you edit the file, a new minified version is created and the old version is removed from the browser cache.

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