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中,这样做是为了调试时查找问题方便(压缩以后就恶心了。。。)
文章请参考: