设为首页 加入收藏

TOP

ASP.NET MVC下Bundle的使用(一)
2017-10-11 13:16:10 】 浏览:4612
Tags:ASP.NET MVC Bundle 使用

ASP.NET MVC中Bundle是用于打包捆绑资源的(一般是css和js),它是在全局文件Global.asax.cs中注册Bundle,而注册的具体实现默认是在App_Start文件夹的BundleConfig.cs中

public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }
BundleConfig.RegisterBundles(BundleTable.Bundles); 在应用程序启用时注册Bundle
public class BundleConfig { // 有关绑定的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301862
    public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // 使用要用于开发和学习的 Modernizr 的开发版本。然后,当你做好 // 生产准备时,请使用 http://modernizr.com 上的生成工具来仅选择所需的测试。
        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } }

为了便于说明,这里在HomeController下新建一个Action,如下:

public ActionResult BundleTest() { return View(); }

这里以使用Bootstrap为例,在视图中使用@Styles.Render() 和@Scripts.Render() 引入css和js,参数是在BundleConfig注册的名称

@{ Layout = null; } <!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>BundleTest</title> @Styles.Render("~/Content/css") </head>
<body> @Scripts.Render("~/bundles/jquery", "~/bundles/bootstrap") </body>
</html>

浏览页面,查看源代码,可以看到:

 

bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css"));

 


由于在BundleConfig.cs中注册上面的Bundle,@Styles.Render("~/Content/css")渲染时是引入~/Content/bootstrap.css和~/Content/site.css,js的渲染同理

为了验证是否真正引入了BootStrap的css与js资源,这里添加了一些简单的BootStrap示例代码,如下:
@{ Layout = null; } <!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>BundleTest</title> @Styles.Render("~/Content/css") </head>
<body>
    <div class="container">
        <div class="header clearfix">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active"><a href="#">首页</a></li>
                    <li role="presentation"><a href="#">关于我们</a></li>
                    <li role="presentation"><a href="#">联系我们</a></li>
                </ul>
            </nav>
        </div>
        <form class="form-horizontal">
            <div class="form-group">
                <label for="us
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇如鹏网学习笔记(十四)ASP.NET 下一篇C#远程调用技术WebService葵花宝典

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目