MVC 通过BundleConfig 将JS和CSS文件引入到视图中

1

App_Start文件夹中的BundleConfig.cs文件

using System.Web;
using System.Web.Optimization;

namespace WebApp
{
    public class BundleConfig
    {
        // 有关绑定的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            //创建一个虚拟目录“~/bundles/jquery” 这个虚拟目录的名字可以随便你取(用一个虚拟路径来初始化Bundle的实例,这个路径并不真实存在)
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        //在虚拟目录中添加了2个绝对路径的js文件
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/jquery.validate.min.js"));

            //创建一个虚拟目录“~/Content/css” 这个虚拟目录的名字是可以随便你取(用一个虚拟路径来初始化Bundle的实例,这个路径并不真实存在)
            bundles.Add(new StyleBundle("~/Content/css").Include(

                      //在虚拟目录中添加了2个css文件
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));



        }


    }
}

Test控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApp.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/
        public ActionResult Index()
        {
            return View();
        }
	}
}

视图

@{
    Layout = null;
}

<!DOCTYPE html>
<!--这样就相当于把BundleConfig.cs文件中bundles.Add(new ScriptBundle("~/bundles/jquery")中添加的js文件全部都引入进来了-->
@Scripts.Render("~/bundles/jquery") 
<!--这样就相当于把BundleConfig.cs文件中 bundles.Add(new StyleBundle("~/Content/css")中添加的css文件全部都引入进来了-->
@Styles.Render("~/Content/css") 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div id="abc"> 
        123
    </div>
</body>
</html>
<script type="text/javascript">
    $(function () {
        alert($("#abc").text());
    })
   
</script>

在ASP.NET MVC4中(在WebForm中应该也有),有一个叫做Bundle的东西,它用来将js和css进行压缩(多个文件可以打包成一个文件),并且可以区分调试和非调试,在调试时不进行压缩,以原始方式显示出来,以方便查找问题。

有一个地方主要注意,在Web.config中,当compilation编译的debug属性设为true时,表示项目处于调试模式,这时Bundle是不会将文件进行打包压缩的,页面中引用的js和css会分散原样的展示在html中,这样做是为了调试时查找问题方便(压缩以后就恶心了。。。)


文章请参考:

在ASP.NET MVC中,使用Bundle来打包压缩js和css

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值