ASP.NET MVC 4 (十一) Bundles和顯示模式

來源:互聯網
上載者:User

標籤:

Bundles用於打包CSS和javascript指令檔,最佳化對它們的組織管理。顯示模式則允許我們為不同的裝置顯示不同的視圖。

預設指令碼庫

在VS建立一個MVC工程,VS會為我們在scripts目錄下添加很多指令碼庫,下面來簡單瞭解下這些指令碼庫的作用:

指令檔 說明
jquery-1.7.1.js jquery的基本類庫
jquery-ui-1.8.20.js jquery的UI類庫,方便我們建立豐富的使用者控制項,基於jquery基本類庫
jquery.mobile-1.1.0.js 用於行動裝置UI控制項的類庫,在建立移動模板的工程時添加
jquery-validate.js  用於用戶端驗證的類庫
knockout-2.1.0.js  用戶端的模型-視圖-視圖模式類庫,在用戶端將顯示資料和沒模型分開,可以認為是瀏覽器上的MVC
modernizr-2.5.3.js  用於檢測瀏覽器對HTML5和CSS3的支援
jquery-1.7.1.intellisense.js  用於Visual studio在編寫jQuery代碼時提供函數名稱的提示
jquery.unobtrusive-ajax.js  用於MVC架構的unobtrusive Ajax功能
jquery.validate-vsdoc.js  用於Visual studio在編寫jQuery驗證函式時提示函數名稱
jquery.validate.unobtrusive.js 用於MVC的用戶端驗證,依賴jquery-validate.js 

一些指令檔有常規和最小化兩個版本,最小化版本刪除注釋剪短變數名以縮小檔案尺寸,在功能上和正常版本一致。正常版本的jquery-1.7.1.js檔案大小252K,而縮小版的jquery-1.7.1.min.js只有92K,如果網站每天數以百萬計的訪問量,帶來的流量節省還是很巨大的。縮小版的指令碼很難閱讀,所以開發時我們使用正常版本的指令碼庫方便調試,發布時再切換為縮小版本。

打包指令碼和風格

Bundles定義在/App_Start/BundleConfig.cs檔案,VS為我們建立的預設實現:

public class BundleConfig {        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725        public static void RegisterBundles(BundleCollection bundles) {            bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include("~/Scripts/jquery-ui-{version}.js"));            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.unobtrusive*","~/Scripts/jquery.validate*"));            // Use the development version of Modernizr to develop with and learn from. Then, when you‘re            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include("~/Scripts/modernizr-*"));            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(                        "~/Content/themes/base/jquery.ui.core.css",                        "~/Content/themes/base/jquery.ui.resizable.css",                        "~/Content/themes/base/jquery.ui.selectable.css",                        "~/Content/themes/base/jquery.ui.accordion.css",                        "~/Content/themes/base/jquery.ui.autocomplete.css",                        "~/Content/themes/base/jquery.ui.button.css",                        "~/Content/themes/base/jquery.ui.dialog.css",                        "~/Content/themes/base/jquery.ui.slider.css",                        "~/Content/themes/base/jquery.ui.tabs.css",                        "~/Content/themes/base/jquery.ui.datepicker.css",                        "~/Content/themes/base/jquery.ui.progressbar.css",                        "~/Content/themes/base/jquery.ui.theme.css"));        }    }

ScriptBundle建立指令碼包,StyleBundle建立CSS風格包,兩者都使用Include包含一組檔案。VS建立的預設包並不一定適合我們的需要,我們可以自行定義:

public class BundleConfig {        public static void RegisterBundles(BundleCollection bundles) {            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/*.css"));            bundles.Add(new ScriptBundle("~/bundles/clientfeaturesscripts")                .Include("~/Scripts/jquery-{version}.js",                        "~/Scripts/jquery.validate.js",                        "~/Scripts/jquery.validate.unobtrusive.js",                        "~/Scripts/jquery.unobtrusive-ajax.js"));        }    }

注意這裡的“~/Scripts/jquery-{version}.js”,{version}匹配對應檔案的任何版本並通過工程設定檔選擇正常版本還是縮小版,具體是web.config中的debug設定,如果為true選擇正常版本,false則是縮小版。需要注意的是我們不能把相同檔案的不同版本號碼放在一起,比如“jquery-1.7.2.js”和“jquery-1.7.1.js”,兩個版本號碼都會被發送給用戶端反而造成混淆。

在布局檔案中使用Scripts.Render()輸出指令碼包,Styles.Render()輸出風格包:

<!DOCTYPE html><html><head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width" />    <title>@ViewBag.Title</title>    @Styles.Render("~/Content/css")</head><body>    @RenderBody()    @Scripts.Render("~/bundles/clientfeaturesscripts")    @RenderSection("scripts", required: false)</body></html>

產生的HTML檔案會通過<link href="XXX" rel="stylesheet"/>包含所有包裡的CSS檔案,所有的指令檔則通過<script src="XXX"></script>引用。

上面的例子中還使用“@RenderSection("scripts", required: false)”輸出一個節,requried=false表示不是必須的,只有在視圖檔案中定義了這個節才會渲染,我們可以利用它來包含視圖需要的額外指令檔,比如我們在MakeBooking.cshtml中定義Scripts節來包含指令檔:

@model ClientFeatures.Models.Appointment@{    ViewBag.Title = "Make A Booking";    AjaxOptions ajaxOpts = new AjaxOptions {        OnSuccess = "processResponse"    };}<h4>Book an Appointment</h4>@section scripts {    <script src="~/Scripts/Home/MakeBooking.js" type="text/javascript"></script>}...

使用這種可選節我們可以有選擇的視圖中包含視圖僅需的指令檔。

面向行動裝置

人們越來越多的使用行動裝置瀏覽網站,MVC應用也要考慮如何相容這些行動裝置以提供的更好的閱讀體驗。我們可以使用安卓、蘋果手機訪問開發測試網站,更方便的是從www.opera.com/developer/tools/mobile下載模仿移動版本的Opera瀏覽器,用它可以模仿不同裝置設定不同螢幕大小的顯示解析度來測試。

在MVC WEB應用中我們在普通的視圖檔案外可以添加面向行動裝置的視圖,視圖檔案名稱裡在檔案尾碼名前加入“.Mobile”表示這是行動裝置專用,比如“/Views/Home/MakeBooking.Mobile.cshtml”:

@model ClientFeatures.Models.Appointment@{    ViewBag.Title = "Make A Booking";    AjaxOptions ajaxOpts = new AjaxOptions {        OnSuccess = "processResponse"    };}<h4>This is the MOBILE View</h4>@section scripts {    <script src="~/Scripts/Home/MakeBooking.js" type="text/javascript"></script>}<div id="formDiv" class="visible">    @using (Ajax.BeginForm(ajaxOpts)) {        @Html.ValidationSummary(true)            <p>@Html.ValidationMessageFor(m => m.ClientName)</p>        <p>Name:</p><p>@Html.EditorFor(m => m.ClientName)</p>        <p>@Html.ValidationMessageFor(m => m.Date)</p>        <p>Date:</p><p>@Html.EditorFor(m => m.Date)</p>        <p>@Html.ValidationMessageFor(m => m.TermsAccepted)</p>        <p>@Html.EditorFor(m => m.TermsAccepted) Terms & Conditions</p>            <input type="submit" value="Make Booking" />    }</div><div id="successDiv" class="hidden">    <h4>Your appointment is confirmed</h4>    <p>Your name is: <b id="successClientName"></b></p>    <p>The date of your appointment is: <b id="successDate"></b></p>    <button id="backButton">Back</button></div>

這裡適當調整控制項布局以更適合在行動裝置上瀏覽,其他和案頭版基本一致。當我們從行動裝置瀏覽時,MVC自動為我們應用移動版本的視圖,MVC依賴C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers目錄下的各種瀏覽器的描述檔案檢查瀏覽器版本,主要是匹配檔案中定義的user agent特性,你會發現UC瀏覽器赫然在列。

自訂顯示模式

上面的方法將所有的行動裝置歸為一類,如果我們還需要更細分具體是哪種行動裝置,我們可以通過建立自訂顯示模式來實現,這是在Application_start中註冊的:

    public class MvcApplication : System.Web.HttpApplication {        protected void Application_Start() {            DisplayModeProvider.Instance.Modes.Insert(0,                new DefaultDisplayMode("OperaTablet") {                    ContextCondition = (context => context.Request.UserAgent.IndexOf("Opera Tablet", StringComparison.OrdinalIgnoreCase) >= 0)                });            AreaRegistration.RegisterAllAreas();...

這裡通過比較請求的User agent是否包含“Opera tablet”來標識OperaTablet顯示模式,如果請求來自於這樣的裝置,MVC會尋找包含OperaTablet的視圖檔案比如/Views/Home/MakeBooking.OperaTable.cshtml,這樣我們就可以單為某種裝置建立自訂的視圖。

 

以上為對《Apress Pro ASP.NET MVC 4》第四版相關內容的總結,不詳之處參見原版 http://www.apress.com/9781430242369。  

ASP.NET MVC 4 (十一) Bundles和顯示模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.