Combining and minifying JS and CSS in ASP.NET MVC

2019-04-06 03:41发布

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!

2条回答
放荡不羁爱自由
2楼-- · 2019-04-06 04:00

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

查看更多
Bombasti
3楼-- · 2019-04-06 04:04

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

查看更多
登录 后发表回答