简体   繁体   中英

Combining and minifying JS and CSS in ASP.NET MVC

I created default ASP.NET MVC 3 web application. Then I added three css and three js files to \\Views\\Shared_Layout.cshtml view:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/StyleSheet1.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/StyleSheet2.css")" rel="stylesheet" type="text/css" />

    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/JScript1.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/JScript2.js")" type="text/javascript"></script>

</head>
<body>
    <div class="page">
        <div id="header">

....

when I run the application, I html code is

<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" />
    <link href="/Content/StyleSheet1.css" rel="stylesheet" type="text/css" />
    <link href="/Content/StyleSheet2.css" rel="stylesheet" type="text/css" />

    <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/JScript1.js" type="text/javascript"></script>
    <script src="/Scripts/JScript2.js" type="text/javascript"></script>

</head>
<body>
    <div class="page">

Is it possible to have a handler in MVC to change my output html to like:

<!DOCTYPE html>
    <html>
    <head>
        <title>Home Page</title>
        <script src="js.axd=/Scripts/jquery-1.5.1.min.js,/Scripts/JScript1.js,/Scripts/JScript2.js" type="text/javascript"></script>
        <link href="css.axd=/Content/Site.css,/Content/StyleSheet1.css,/Content/StyleSheet2.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <div class="page">

So the link js.axd=/Scripts/jquery-1.5.1.min.js,/Scripts/JScript1.js,/Scripts/JScript2.js will return content of all these js files to the browser, and link css.axd=/Content/Site.css,/Content/StyleSheet1.css,/Content/StyleSheet2.css will return content of all css files.

I did something before in ASP.NET by IHttpHandler, but can't figure out how to do that in MVC, since I'm just starter in MVC.

Any help and code samples will appreciate. Thank you!

You can use bundle and minification nuget package. Bundling and Minification

At the NuGet console type: "Install-Package Microsoft.AspNet.Web.Optimization"

Example here:

Using Web Optimization with MVC 3

I use cassette in my own projects. Also, this list here contains top 20 in Nuget.

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