[Go] Create a view optimized for mobile devices in ASP. NET MVC 4

Source: Internet
Author: User

Original link https://msdn.microsoft.com/zh-cn/magazine/dn296507.aspx

If you delve into the common sense considerations for writing mobile device sites, you'll find an intrinsic contradiction. on the one hand, customers strongly demand (or are willing to require) mobile priority in their methods of writing applications and websites. On the other hand, the same people often praise CSS media queries and fluid layout. The paradox I've found is that it's not a move-first approach to often use CSS media queries and fluid layouts that don't prioritize mobility before other content. In this article, I'll show you how to use server-side logic to render the best display for a given device, and introduce a new feature of ASP. NET MVC 4, called display mode.

The problem is not in CSS media queries as a technology.   So, how do you turn the use of CSS media queries and fluid layouts into a" move-first "approach?   In this perspective, use CSS (a client-side technology) to switch between views, and use the JavaScript further adjusts the view when the CSS is not competent.

Therefore, you may not be able to provide the best experience to the user.   I think you should make a reasonable effort to have only one codebase (common ground for Web APIs), But be sure to focus on the specific usage of each type of device that you want to support.   "mobile" has become a narrow word now, by smartphones, tablets, Many types of devices, such as laptops and smart TVs, are replaced, not to mention wearable devices such as spectacle monitors and smart watches.

About a year ago, in this column, I showed a server-side approach to developing an asp: to create a temporary view for each type of device supported ("Mobile Site development: Markup" msdn.microsoft.com/magazine/jj133814). I was doing this in an ASP. NET MVC 3 environment. ASP. NET MVC 4 is fully qualified for this task, with the previously mentioned display mode, which makes it easy to implement server-side logic that provides the best view and content for a given device. to be effective, this approach requires you to learn as much as possible about the capabilities of the requesting device. However, other content is not detected on the client, except for basic information about the screen size and current orientation. then, you need to use the server repository for device information.

introducing display modes in ASP. NET MVC 4

Before I begin to delve into the display mode, let me state in advance that this article (and the display mode technology itself) primarily involves generating a unique new site that dynamically binds the same URL to different views. If you already have a website to provide an affiliate website optimized for some (mobile) devices, that's another topic. you can still use this column as a guide to building a satellite site, but you will need additional tools for unifying URLs with existing parent sites.

in ASP. NET MVC 4, the display mode is a system feature that extends the traditional behavior of the view engine so that it can pick the view file that best suits the requesting device. In the previously mentioned ASP 3 article, I used a custom view engine for this purpose. In This solution, I can only use the Razor view. with the display mode, the Controller method will still be called, for example, a view named Index, and if the device is known to be a mobile device, the ASP. NET MVC runtime will instead pick a view file named Index.mobile.cshtml.

This is a good news, because it means that the site can still have only one codebase. simply add additional CSHTML view files for each type of device that you want to support. to get started with display mode, let's take a look at the code example in Figure 1 .

Figure 1: Standard list of supported display modes

The page in the code in Figure 1 shows a standard list of supported display modes. Figure 2 shows the output generated by the page.


Figure 2: Default list of display modes

The ASP. NET MVC 4 display mode follows several conventions. in particular, each display mode is associated with a keyword. This keyword is used to make up the name of the corresponding view file. The default display mode is bound to an empty string. Therefore, the following view files are handled correctly by any ASP. NET MVC 4 application without your further intervention: index.cshtml and index.mobile.cshtml.

To see the demo, copy the index.cshtml file to a new file named Index.mobile.cshtml, and then add it to your project. To differentiate these two files, add the following to the move file:

<div style= "border-bottom:solid 1px #000" >mobile view</div>

If you run the application and test it using Internet Explorer or another desktop browser, there is no change. try pressing F12 to display the Internet Explorer developer tools, and then by selecting the Tools | Change the user agent string, set the Mobile User agent (UA), as shown in Figure 3 .


Figure 3: Forcing Internet Explorer to test with a mobile user agent

I have configured UA for several mobile phones and tablets. For example, you can use the following content, which identifies the requesting browser as an HTC Desire Android smartphone:

mozilla/5.0 (Linux; U Android 2.1; XX-XX; HTC Desire Build/ere27) applewebkit/525.10+ (khtml, like Gecko) version/3.0.4 Mobile safari/523.12.2

Figure 4 shows what you get from the ASP. 4 Web site. The page obtained from the same pair of controllers and operations is index.mobile.cshtml. More importantly, you don't need to make any changes to your programming style, and you don't have to learn any new skills to get this effect.


Figure 4: Switch to Mobile view

Beyond the Basics

So far, what we've discussed is just the most basic work that can be done and should be done when developing a mobile site. You need to address the important two points in order to turn the display mode into a real site solution. The point is to explore ways to add multiple display modes. The other is exploring ways to inject some temporal logic to more reliably detect devices.

The built-in logic for detecting mobile devices is not all that reliable for ASP. the logic is likely to apply to most smartphones, but not to older phones. take the following UA as an example:

Samsung-gt-s3370/s3370ddjd4 shp/vpp/r5 dolfin/1.5 qtv/5.3smm-mms/1.2.0 profile/midp-2.1 configuration/CLDC-1.1 OPN-N

This phone does not support Wi-Fi connection, but its ability to render HTML is surprisingly good.   its screen is smaller than most smartphones, but it supports touch.   This has two drawbacks.   First, the user is almost unable to view the content because the content will be stretched and revolved around the screen for four weeks.   second, a lot of content will be downloaded, and since this phone does not support Wi-Fi connection, it is likely through 3G The connection downloads all of this content, so the process is certainly slow and the user may spend more money.

When I mention this, some people say their site just doesn't support these types of old-fashioned phones. This certainly makes sense, but is it better to send a polite message to the user in this case instead of letting the situation get out of control? in order to be able to send a "sorry, unable to view this site on your device" message, still need to correctly identify the device, and understand it and, for example, the IPhone, different. In addition, the ability to safely ignore old-fashioned devices is a business (not an implementation) decision. the impact on the business of not providing services to a few generations of equipment may be beyond imagination. So, here's how to add multiple display modes to a Web site to properly service multiple types of devices.

Device Type

"best possible experience" means providing temporary usage, selected data, and specific features.   The resulting token must be device specific.   If you adjust the settings on the client, you actually get a unified version of the page when you rely on CSS media queries , and then just tweak the pages to fit the smaller screen.   This usually means hiding some blocks, covering the other blocks in the vertical direction, It is also possible to request a lower set of visual effects.   The unified version of the page is usually the desktop page.   Personally, I don't want to call this a move-first approach.

Speaking of "device type", I have no intention of distinguishing between iPhone devices and Windows Phone devices. instead, it is designed to use logic that provides different tags to smartphones, tablets, and laptops. therefore, in ASP. 4, I want to use at least three display modes: Smartphone, tablet, and default mode (for desktop browsers). I'll add another Displayconfig class to call in App_start (see Figure 5).

Figure 5:displayconfig Class

 public class displayconfig{public static void Registerdisplaymodes (ilist<idisplaymode> displaymodes) {VA   R modedesktop = new Defaultdisplaymode ("") {contextcondition = (c = c.request.isdesktop ())};   var modesmartphone = new Defaultdisplaymode ("smart") {contextcondition = (c = C.request.issmartphone ())};   var modetablet = new Defaultdisplaymode ("tablet") {contextcondition = (c = C.request.istablet ())};   Displaymodes.clear ();   Displaymodes.add (Modesmartphone);   Displaymodes.add (Modetablet); Displaymodes.add (Modedesktop); }}

this way, it removes the default mode.   Next, the code populates the provided system collection with the newly created display mode list.   A new display mode is an instance of the Defaultdisplaymode class.  

The Contextcondition property is a delegate that accepts a HttpContextBase object and returns a Boolean value. The principal of the delegate captures the HTTP context of the current request to determine whether a given display mode is appropriate. in Figure 5 , I used some extension methods to make the code more readable. Figure 6 lists these extension methods.

Figure 6: An extension method that keeps code concise

public static class httprequestbaseextensions{public  static Boolean Isdesktop (this httprequestbase request)  {    return true;  }  public static Boolean Issmartphone (this httprequestbase request)  {    return issmartphoneinternal (Request). useragent);  }  public static Boolean Istablet (this httprequestbase request)  {    return istabletinternal (Request). useragent);  }  More code here.}

All the code discussed so far is simply the infrastructure. Finally, write a method for each display mode. Each method takes a UA and returns a Boolean reply. here is a very basic routine to check whether it is a tablet:

private static Boolean istabletinternal (String useragent) {  var ua = Useragent.tolower ();  Return UA. Contains ("ipad") | | Ua. Contains ("gt-");}

Although this routine can only guarantee successful detection of the IPAD and Galaxy Tab devices, you can learn the essentials of how these context condition routines should be written. at the very least, you may want to add more code to check whether it is a smartphone. to detect tablets and smartphones, you can leverage any open source or commercial device description Repository (DDR) framework. I'll discuss this in more detail in the next column.

official business

The server-side approach to mobile web sites is not always necessary, but it is a serious matter when you run some business behind a website. I don't want to recommend server-side methods for, for example, a conference site or any kind of short-term website. However, business sites targeting the widest possible audience need to focus on optimizing for a variety of devices, rather than simply presenting content that is appropriate for the mobile environment.

On the client side, you are limited to the browser window size and orientation, and you cannot check the operating system or touch features, nor can you check for more advanced features such as whether the device supports wireless, streaming, inline images, text messages, and so on. The display mode makes it particularly easy to implement a multi-view approach in ASP. NET MVC 4.

In the next column, I'll discuss how to integrate the DDR (Wireless Universal Resource file (WURFL)) used by Facebook with ASP. 4.

Dino Esposito is "architecting Mobile Solutions for the Enterprise" (Microsoft PRESS,2012) and Programming ASP 3 (Microsoft Pre ss,2011) is also the author of Microsoft. Co-author of net:architecting Applications for the Enterprise (Microsoft press,2008 year). Esposito is a resident in Italy and often speaks in industry events around the world. For his information, please visit Twitter Twitter.com/despos.

Heartfelt thanks to the following technical experts for reviewing this article: Mani Subramanian (Microsoft)
Mani Subramanian has been involved in the development and testing of software projects for the past 12 years, with a focus on SOA, cloud computing and core.net.

[Go] Create a view optimized for mobile devices in ASP. NET MVC 4

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.