The world in which we live is changing rapidly. Almost everyone now seems to own a smartphone, a tablet, or both, and we spend a lot of our time (too much?) viewing web sites on these devices. This trend has created a challenge for developers because mobile browsers and desktop browsers behave differently. Adding to that challenge is the fact that there is a plethora of devices with different form factors. Building web applications that look good and are fully functional on these devices can quickly become a titanic task.
ASP.NET MVC 4 introduces a new set of features that is intended to help developers create web applications that work seamlessly both in desktop browsers and in mobile browsers. Views can now be created to target specific browsers. Also, with the help of CSS3, we can apply styles based on the form factor of the device.
Let me start by saying that, to provide the best user experience across desktop and mobile browsers, you should work with HTML5 for the markup and CSS3 for the styling of elements. The _Layout.cshtml view is built with HTML5. You can quickly identify in the listing the enhanced HTML5 markup, known as semantic markup, with tags such as <header>, <footer>, <nav>, <section>, and a simplified <!DOCTYPE html>.
Another important aspect of mobile browsers is the viewport, a virtual browser window that is defined in most mobile browsers. This virtual window is normally defined with dimensions that are larger than the actual device screen, which allows users to zoom in on page content that is of interest. If the viewport, on the other hand, is defined by the developer with the actual device screen dimensions, then zooming is not available as the content in the page is supposed to fit correctly.
We can control the viewport using a <meta> tag in the <head> section of a web page:
<meta name="viewport" content="width=device-width">
This tag instructs the mobile browser to set the width of the viewport to the actual width of the device’s screen. This is achieved with the constant device-width, whose value is defined in every device with the screen’s width. This is important because we want to provide to mobile users a version of the web application that is suitable for their devices, not just the full desktop version with zoom capabilities.
To provide styles for specific form factors, we need to implement CSS3 media queries. A media query is nothing more than a definition of a type of media and a set of characteristics for the media. A type of media identifies the means by which a page is viewed (for example, onscreen or printed). The characteristics of the media may be, for example, the screen dimensions and whether or not the media supports colors.
The default ASP.NET MVC 4 Internet Application project template that we are using for our sample application includes in the Content directory a CSS style sheet called Site.css. If you open the file, you will find the following media query:
@media only screen and (max-width: 850px){
...
// set of styles when the media query is applied
...
}
The media query specifies that it will apply the set of styles only when the application is viewed onscreen. This means that if the page is printed, for example, then the styles won’t be printed. Also, the media characteristics state that the maximum width is 850 pixels. The browser interprets this as, “If the page is viewed in a screen with a width of 850 pixels or less, then apply the following set of styles.”
Listing 1 shows a few modifications I added to the Site.css file to clearly show the difference between rendering a view in a desktop browser (see Figure 1) and rendering a view in a mobile browser (see Figure 2).
Listing 1. Modifications to the Media Query in Site.css File
.main-content,
.featured + .main-content {
background-position: 10px 0;
background-image: none;
}
.featured .content-wrapper {
padding: 10px;
background-color: #e80c4d;
background-image: -ms-linear-gradient(left, #e80c4d 0%, #e6507d 100%);
background-image: -o-linear-gradient(left, #e80c4d 0%, #e6507d 100%);
background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #e80c4d),
color-stop(1, #e6507d));
background-image: -webkit-linear-gradient(left, #e80c4d 0%, #e6507d 100%);
background-image: linear-gradient(left, #e80c4d 0%, #e6507d 100%);
color: #fff;
}

Figure 1. View rendered in Chrome desktop browser on a Windows computer

Figure 2. View rendered in Mobile Chrome running in iOS
You can immediately see the differences between the browsers and how the media query affected the way styles were applied. The desktop version has a light blue background for the main, featured-content area, and the header is split in left and right sections (the left section for the site title and the right section for the menu options). In the mobile version, the light blue background is changed to fuchsia and the header is simplified and placed in a single stacked column for all the menu options.
There is another difference that probably didn’t catch your eye at first glance. In Figure 5-6, the featured section reads “Home Page,” but in Figure 5-7, the mobile browser says “Mobile Home Page.” How did that happen? CSS media queries cannot do that. That is a feature in ASP.NET MVC 4 called view override , a simple mechanism in which ASP.NET MVC identifies that the request is made by a mobile browser. It does only that—recognizes that a mobile browser made the request.
To override a view, you need to create a view that ends with .Mobile.cshtml, as opposed to the normal desktop browser views, which just use .cshtml. The examples shown in Figures 1 and 2 use the views shown in Figure 3.

Figure 3. Views used to implement view override
With this simple mechanism, you can provide a much better experience to users who are using mobile browsers. You don’t need to mix code, HTML markup, and CSS styles in a single view to handle different browsers. The mobile version of the view can be completely different from the desktop version, both from the style perspective and in the content it presents. In an extreme case, you could even use the mobile browser view simply to tell the user to use a desktop browser because the content cannot be correctly viewed in a mobile browser.
One thing that view override cannot do is identify a specific browser or a specific platform. For that, we need to create a custom display mode. Let’s say, for example, that we want to target specifically browsers in iPhones. To do so, we need to do two things: first, add the new display mode in the Application_Start event in the Global.asax.cs file, and then create a new view that targets the specific display mode.
Listing 2 adds a new display mode object identified as iPhone to the DisplayModeProvider. The new display mode object defines which properties it wants to recognize in the browser in order to render the view with the ContextCondition property. The condition states that if the information in the UserAgent piece passed by the browser in the request has the word “iPhone” (ignoring all casing rules), then the requested view should be rendered with the iPhone version.
Listing 2. Creating a Custom Display Mode to Target iPhone Mobile Browsers
using System;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.WebPages;
namespace HaveYouSeenMe {
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start(){
DisplayModeProvider.Instance.Modes
.Insert(0, new DefaultDisplayMode("iPhone")
{
ContextCondition = (context =>
context.GetOverriddenUserAgent().IndexOf
("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
In Listing 2, we are creating a new DefaultDisplayMode with the name iPhone. This tells the ASP.NET MVC 4 framework to look for views in files whose names end with .iPhone.cshtml. If we want a view with file name Index.cshtml to render differently in iPhone devices, then we need to create a version of the view named Index.iPhone.cshtml, as shown in Figure 4.

Figure 4. New view to be rendered when a request is made from iPhone devices
For our example, I made a simple change in the view content to indicate that it is the view to be rendered in iPhone devices. The result is shown in Figure 5.

Figure 5. View rendered in an iPhone
ASP.NET MVC 4 introduces a new set of features that is intended to help developers create web applications that work seamlessly both in desktop browsers and in mobile browsers. Views can now be created to target specific browsers. Also, with the help of CSS3, we can apply styles based on the form factor of the device.
Let me start by saying that, to provide the best user experience across desktop and mobile browsers, you should work with HTML5 for the markup and CSS3 for the styling of elements. The _Layout.cshtml view is built with HTML5. You can quickly identify in the listing the enhanced HTML5 markup, known as semantic markup, with tags such as <header>, <footer>, <nav>, <section>, and a simplified <!DOCTYPE html>.
Another important aspect of mobile browsers is the viewport, a virtual browser window that is defined in most mobile browsers. This virtual window is normally defined with dimensions that are larger than the actual device screen, which allows users to zoom in on page content that is of interest. If the viewport, on the other hand, is defined by the developer with the actual device screen dimensions, then zooming is not available as the content in the page is supposed to fit correctly.
We can control the viewport using a <meta> tag in the <head> section of a web page:
<meta name="viewport" content="width=device-width">
This tag instructs the mobile browser to set the width of the viewport to the actual width of the device’s screen. This is achieved with the constant device-width, whose value is defined in every device with the screen’s width. This is important because we want to provide to mobile users a version of the web application that is suitable for their devices, not just the full desktop version with zoom capabilities.
To provide styles for specific form factors, we need to implement CSS3 media queries. A media query is nothing more than a definition of a type of media and a set of characteristics for the media. A type of media identifies the means by which a page is viewed (for example, onscreen or printed). The characteristics of the media may be, for example, the screen dimensions and whether or not the media supports colors.
The default ASP.NET MVC 4 Internet Application project template that we are using for our sample application includes in the Content directory a CSS style sheet called Site.css. If you open the file, you will find the following media query:
@media only screen and (max-width: 850px){
...
// set of styles when the media query is applied
...
}
The media query specifies that it will apply the set of styles only when the application is viewed onscreen. This means that if the page is printed, for example, then the styles won’t be printed. Also, the media characteristics state that the maximum width is 850 pixels. The browser interprets this as, “If the page is viewed in a screen with a width of 850 pixels or less, then apply the following set of styles.”
Listing 1 shows a few modifications I added to the Site.css file to clearly show the difference between rendering a view in a desktop browser (see Figure 1) and rendering a view in a mobile browser (see Figure 2).
Listing 1. Modifications to the Media Query in Site.css File
.main-content,
.featured + .main-content {
background-position: 10px 0;
background-image: none;
}
.featured .content-wrapper {
padding: 10px;
background-color: #e80c4d;
background-image: -ms-linear-gradient(left, #e80c4d 0%, #e6507d 100%);
background-image: -o-linear-gradient(left, #e80c4d 0%, #e6507d 100%);
background-image: -webkit-gradient(linear, left top, right top, color-stop(0, #e80c4d),
color-stop(1, #e6507d));
background-image: -webkit-linear-gradient(left, #e80c4d 0%, #e6507d 100%);
background-image: linear-gradient(left, #e80c4d 0%, #e6507d 100%);
color: #fff;
}
Figure 1. View rendered in Chrome desktop browser on a Windows computer
Figure 2. View rendered in Mobile Chrome running in iOS
You can immediately see the differences between the browsers and how the media query affected the way styles were applied. The desktop version has a light blue background for the main, featured-content area, and the header is split in left and right sections (the left section for the site title and the right section for the menu options). In the mobile version, the light blue background is changed to fuchsia and the header is simplified and placed in a single stacked column for all the menu options.
There is another difference that probably didn’t catch your eye at first glance. In Figure 5-6, the featured section reads “Home Page,” but in Figure 5-7, the mobile browser says “Mobile Home Page.” How did that happen? CSS media queries cannot do that. That is a feature in ASP.NET MVC 4 called view override , a simple mechanism in which ASP.NET MVC identifies that the request is made by a mobile browser. It does only that—recognizes that a mobile browser made the request.
To override a view, you need to create a view that ends with .Mobile.cshtml, as opposed to the normal desktop browser views, which just use .cshtml. The examples shown in Figures 1 and 2 use the views shown in Figure 3.
Figure 3. Views used to implement view override
With this simple mechanism, you can provide a much better experience to users who are using mobile browsers. You don’t need to mix code, HTML markup, and CSS styles in a single view to handle different browsers. The mobile version of the view can be completely different from the desktop version, both from the style perspective and in the content it presents. In an extreme case, you could even use the mobile browser view simply to tell the user to use a desktop browser because the content cannot be correctly viewed in a mobile browser.
One thing that view override cannot do is identify a specific browser or a specific platform. For that, we need to create a custom display mode. Let’s say, for example, that we want to target specifically browsers in iPhones. To do so, we need to do two things: first, add the new display mode in the Application_Start event in the Global.asax.cs file, and then create a new view that targets the specific display mode.
Listing 2 adds a new display mode object identified as iPhone to the DisplayModeProvider. The new display mode object defines which properties it wants to recognize in the browser in order to render the view with the ContextCondition property. The condition states that if the information in the UserAgent piece passed by the browser in the request has the word “iPhone” (ignoring all casing rules), then the requested view should be rendered with the iPhone version.
Listing 2. Creating a Custom Display Mode to Target iPhone Mobile Browsers
using System;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.WebPages;
namespace HaveYouSeenMe {
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start(){
DisplayModeProvider.Instance.Modes
.Insert(0, new DefaultDisplayMode("iPhone")
{
ContextCondition = (context =>
context.GetOverriddenUserAgent().IndexOf
("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)
});
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
}
In Listing 2, we are creating a new DefaultDisplayMode with the name iPhone. This tells the ASP.NET MVC 4 framework to look for views in files whose names end with .iPhone.cshtml. If we want a view with file name Index.cshtml to render differently in iPhone devices, then we need to create a version of the view named Index.iPhone.cshtml, as shown in Figure 4.
Figure 4. New view to be rendered when a request is made from iPhone devices
For our example, I made a simple change in the view content to indicate that it is the view to be rendered in iPhone devices. The result is shown in Figure 5.
Figure 5. View rendered in an iPhone
No comments:
Post a Comment