ASP. NET MVC 4 (11) Bundles and display mode

Source: Internet
Author: User

Bundles is used to package CSS and JavaScript script files to optimize the organization and management of them. The display mode allows us to display different views for different devices.

Default Script Library

In vs Creating an MVC project, VS will add a lot of script libraries to our scripts directory, here's a quick look at the role of these scripting libraries:

Script file Description
Jquery-1.7.1.js Basic Class library for jquery
Jquery-ui-1.8.20.js jquery's UI class library allows us to create rich user controls, based on the jquery base class library
Jquery.mobile-1.1.0.js Class library for mobile device UI controls, adding when creating a project to move a template
Jquery-validate.js Class library for client-side validation
Knockout-2.1.0.js Client-side Model-View-View mode class library, where the client will display the data and no model separately, can be considered as MVC on the browser
Modernizr-2.5.3.js Used to detect browser support for HTML5 and CSS3
Jquery-1.7.1.intellisense.js Tips for Visual Studio to provide function names when writing jquery code
Jquery.unobtrusive-ajax.js Unobtrusive Ajax features for the MVC framework
Jquery.validate-vsdoc.js For Visual Studio to prompt for function names when writing jquery validation functions
Jquery.validate.unobtrusive.js Client-side validation for MVC, relying on jquery-validate.js

Some script files have regular and minimized two versions, minimal version deletion notes cut short variable names to reduce file size, functionally and in line with normal version. The normal version of the Jquery-1.7.1.js file size is 252K, while the smaller version of the jquery-1.7.1.min.js only 92K, if the site millions of visits per day, the resulting traffic savings is still very large. The smaller version of the script is difficult to read, so we use the normal version of the script library to facilitate debugging, and then switch to a smaller version when publishing.

Packaging Scripts and styles

Bundles defined in the/app_start/bundleconfig.cs file, VS creates the default implementation for us:

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 if you ' re/production, use the build tool at http://modernizr.com to pick only the tests yo            u 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/jquer Y.ui.dialog.css "," ~/content/themes/base/jquery.ui.slider.css "," ~/content/t                        Hemes/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 Create a script package, stylebundle create a CSS style package, both use the include to contain a set of files. The default package created by VS does not necessarily fit our needs, and we can define it ourselves:

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 "));        }    }

Note here that the "~/scripts/jquery-{version}.js", {version}, matches any version of the corresponding file and chooses the normal version or the smaller version from the project configuration file. Specifically, the debug setting in Web. config, if the normal version is selected for True, False is the smaller version. It is important to note that we cannot put together different version numbers of the same file, such as "Jquery-1.7.2.js" and "Jquery-1.7.1.js", and two version numbers will be sent to the client instead of confusing.

Using the Scripts.render () output script package in the layout file, the Styles.render () Output Style pack:

<! DOCTYPE html>    @Styles. Render(" ~/content/ CSS ") @Scripts. Render(" ~/bundles/clientfeaturesscripts ")    @RenderSection (" Scripts ", Required:false) </body>

The generated HTML file will be <link href= "xxx" rel= "stylesheet"/> contains all the CSS files in the package, all the script files through <script src= "xxx" ></script > References.

The example above also uses "@RenderSection (" Scripts ", Required:false)" To output a section, Requried=false is not required, only the section defined in the view file will be rendered, We can use it to include additional script files that the view requires, such as we define the scripts section in makebooking.cshtml to include the script file:

@model clientfeatures.models.appointment@{    viewbag.title = "Make A Booking";    Ajaxoptions ajaxopts = new Ajaxoptions {        onsuccess = "ProcessResponse"    };} 

With this optional section we can have a selected view that contains only the script files that the view requires.

For mobile devices

More and more people are using mobile devices to browse websites, and MVC applications have to consider how they can be compatible with these mobile devices to provide a better reading experience. We can use Android, Apple mobile phone to visit the development test site, more convenient is to download from Www.opera.com/developer/tools/mobile copy of the mobile version of the Opera browser, it can imitate different devices set different screen size display resolution to test.

In the MVC Web App we can add a view of the mobile device outside the normal view file, and in the view file name, in front of the file suffix, add ". Mobile "means that this is a device-specific, such as"/views/home/makebooking.mobile.cshtml ":

@model clientfeatures.models.appointment@{viewbag.title = "Make A Booking"; Ajaxoptions ajaxopts = new Ajaxoptions {onsuccess = "processresponse"};} 

The layout of the controls is appropriately adjusted to be more suitable for browsing on mobile devices, and the rest is basically consistent with the desktop version. When we browse from a mobile device, MVC automatically applies the mobile version of the view to us, and MVC relies on C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\ The description file of various browsers under the browsers directory checks the browser version, primarily the user Agent feature defined in the matching file, and you will find the UC browser impressively listed.

Custom display Mode

The above methods classify all mobile devices as a class, and if we need to subdivide what kind of mobile device, we can do this by creating a custom display mode, which is registered in 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 ();..

This is done by comparing whether the requested user agent contains "Opera tablet" to identify the Operatablet display mode, and if the request comes from such a device, MVC looks for a view file that contains operatablet such as/views/home/ MakeBooking.OperaTable.cshtml, so that we can create a custom view for a single device.

ASP. NET MVC 4 (11) Bundles and display mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.