Você está na página 1de 14

qwertyuiopasdfghjklzxcvbnmqwer tyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjk How to add Mobile Pages to your application lzxcvbnmqwertyuiopasdfghjklzxcv bnmqwertyuiopasdfghjklzxcvbnm qwertyuiopasdfghjklzxcvbnmqwer tyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasd

fghjklzxcvbnmqwertyuiopasdfghjk lzxcvbnmqwertyuiopasdfghjklzxcv bnmqwertyuiopasdfghjklzxcvbnm qwertyuiopasdfghjklzxcvbnmqwer tyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmrtyuiopasdfghjklzxc

2/12/2011 Kamakshi Pant

Mobile devices smart phones, feature phones, and tablets continue to grow in popularity as a means to access the Web. The infrastructure that supports "Wireless web is becoming larger and more reliable with the advent of time. For many web developers and web-oriented businesses, this means its increasingly important to provide a great browsing experience for visitors using those devices. These days mobile devices are part of our life style and most of us cant live with out them. When these mobile devices are connected to the Internet, the powers of the mobile devices are endless. We can deliver timely data to the user at any place and any time. Traditionally mobile applications are developed using WML, WMLScript and WBMP with a server. For dynamic WML applications, developers used ASP, JSP, PHP, etc. Still these applications serve WML on the fly. The Mobile Devices includes Cell Phones, Two Way Pagers, Palm Pilots, Pocket PCs and Auto PCs. Few of these devices support WML, few support HTML and few support both WML and HTML. If we want to satisfy all the mobile devices then we must build your application in both WML and limited HTML. ASP.NET has provided the facility to develop Mobile Pages since its Version V2.0, however with time the usage became more and more easier. Infact in the latest V4.0 these features are in built. This Paper describes various ways to serve pages optimized for mobile devices from your ASP.NET Web Forms / MVC application, and suggests architectural and design issues to consider when targeting a broad range of devices. This document also explains why the ASP.NET Mobile Controls from ASP.NET 2.0 to 3.5 are now obsolete, and discusses some modern alternatives.

2. The challenges of supporting mobile devices today

Even though mobile browsers now almost universally support HTML, you will still face many challenges when aiming to create great mobile browsing experiences:

Screen size - Mobile devices vary dramatically in form, and their screens are often much smaller than desktop monitors. So, you may need to design completely different page layouts for them. Input methods Some devices have keypads, some have styluses, others use touch. You may need to consider multiple navigation mechanisms and data input methods. Standards compliance Many mobile browsers do not support the latest HTML, CSS, or JavaScript standards. Bandwidth Cellular data network performance varies wildly, and some end users are on tariffs that charge by the megabyte.

Theres no one-size-fits-all solution; the application will have to look and behave differently according to the device accessing it. Depending on what level of mobile support one wants, this can be a bigger challenge for web developers than the desktop browser wars ever was. Developers approaching mobile browser support for the first time often initially think its only important to support the latest and most sophisticated smart phones (e.g., Windows Phone 7, iPhone, or Android), perhaps because developers often personally own such devices. However, cheaper phones are still extremely popular, and their owners do use them to browse the web especially in countries where mobile phones are easier to get than a broadband connection. The business will need to decide what range of devices to support by considering its likely customers. For eg: If an online brochure for a luxury health spa is to be build , then business might make a decision only to target advanced smart phones, whereas if a ticket booking system for a cinema is to be created, then visitors with less powerful feature phones are to be accounted for.

3. Options to Add Mobile Pages

Before we get to the specific technical details of ASP.NET Web Forms or MVC, we should note that web developers in general have three main possible options for supporting mobile browsers:

1. Do nothing You can simply create a standard, desktop-oriented web application, and

rely on mobile browsers to render it acceptably. o Advantage: Its the cheapest option to implement and maintain no extra work o Disadvantage: Gives the worst end-user experience: The latest smartphones may render your HTML just as well as a desktop browser, but users will still be forced to zoom and scroll horizontally and vertically to consume your content on a small screen. This is far from optimal. Older devices and feature phones may fail to render your markup in a satisfactory way. 2. Solve the problem on the client With careful use of CSS and progressive enhancement you can create markup, styles, and scripts that adapt to whatever browser is running them. For example, with CSS 3 media queries, you could create a multi-column layout that turns into a single column layout on devices whose screens are narrower than a chosen threshold. o Advantage: Optimizes rendering for the specific device in use, even for unknown future devices according to whatever screen and input characteristics they have

Advantage: Easily lets you share server-side logic across all device types minimal duplication of code or effort o Disadvantage: Mobile devices are so different from desktop devices that you may really want your mobile pages to be completely different from your desktop pages, showing different information. Such variations can be inefficient or impossible to achieve robustly through CSS alone, especially considering how inconsistently older devices interpret CSS rules. This is particularly true of CSS 3 attributes. o Disadvantage: Provides no support for varying server-side logic and workflows for different devices. You cant, for example, implement a simplified shopping cart checkout workflow for mobile users by means of CSS alone. o Disadvantage: Inefficient bandwidth use. You server may have to transmit the markup and styles that apply to all possible devices, even though the target device will only use a subset of that information. 3. Solve the problem on the server If your server knows what device is accessing it or at least the characteristics of that device, such as its screen size and input method, and whether its a mobile device it can run different logic and output different HTML markup. o Advantage: Maximum flexibility. Theres no limit to how much you can vary your server-side logic for mobiles or optimize your markup for the desired, devicespecific layout. o Advantage: Efficient bandwidth use. You only need to transmit the markup and styling information that the target device is going to use. o Disadvantage: Sometimes forces repetition of effort or code (e.g., making you create similar but slightly different copies of your Web Forms pages or MVC views). Where possible you will factor out common logic into an underlying layer or service, but still, some parts of your UI code or markup may have to be duplicated and then maintained in parallel. o Disadvantage: Device detection is not trivial. It requires a list or database of known device types and their characteristics (which may not always be perfectly up-to-date) and isnt guaranteed to accurately match every incoming request. This document describes some options and their pitfalls later.

To get the best results, most developers find they need to combine options (2) and (3). Minor stylistic differences are best accommodated on the client using CSS or even JavaScript, whereas major differences in data, workflow, or markup are most effectively implemented in server-side code. Since ASP.NET Web Forms and MVC are both primarily server-side technologies, this white paper will focus on server-side techniques that let produce different markup and logic for mobile browsers. Of course, you can also combine this with any client-side technique (e.g., CSS 3 media queries, progressive-enhancement JavaScript), but thats more a matter of web design than ASP.NET development.

4. Developing Mobile Web Pages using Asp.net 2.0/3.5

Developing ASP.NET pages for mobile device browsers does not differ substantially from developing pages for desktop browsers. To help in creating applications for mobile devices, ASP.NET provides a System.Web.Mobile namespace devoted specifically to mobile Web development.

We can create a Web page from the MobilePage base class and add controls from the System.Web.Mobile namespace. This namespace defines a suite of Web server controls and adapters that are especially useful when creating applications that need to be available to many different mobile devices, such as cell phones. ASP.NET 2.0 also provides a control-adaptive architecture that allows custom device adapters to be created for ASP.NET 2.0 Web server controls. The adapters can create custom rendering for a control based on the requesting browser. With the adaptive architecture, you can create custom adapters for ASP.NET Web server controls to render output specific to the devices that access your application on desktop browsers. Whether developing for desktop browsers or mobile devices, development follows the standard .NET event-driven model in which your application responds to user requests, button clicks, and so on.


Mobile Application Architecture

Although ASP.NET integrates technology to make ASP.NET mobile Web application development follow the same paradigm as traditional Web application development, the architecture's primary intent is not to allow you to create single pages that can target browsers in both desktop and mobile devices. The limitations of browsers on mobile devices often mean that pages designed for desktop browsers cannot translate to mobile device browsers. For example, if you create an ASP.NET Web page that includes a site header, a navigation bar along the top of the page, a secondary navigation structure along the side of the page, and then content in the rest of the page, the page will render as designed in a desktop browser. In that case, there is usually ample space to render all the controls and still provide a scrollable content area. However, in many mobile device browsers, this layout would be impossible. Many mobile devices have a smaller screen area than desktop monitors, so even navigation becomes a multi-step process in which the user must click several controls to get to page content. Presentation logic follows a similar pattern. For example, when the user fills in a Web form using a desktop browser, the user can see many controls on the screen at once. When the form is validated on the server, validation errors can be displayed next to the controls. With a mobile device, form input and validation can be much harder to display in a format that is usable. Additionally, for mobile devices you might choose to provide shortcuts that allow the user to fill in information with less typing because the device might be difficult to type on. For these reasons, you must create separate pages in your ASP.NET Web application for use in desktop and mobile device browsers. A page developed specifically for mobile device browsers allows you to break down presentation logic into smaller pieces that work better for the device's display area and input hardware.


Mobile Web Server Controls

The ASP.NET 2.0 System.Web.Mobile namespace is devoted specifically to mobile Web development. You create a mobile Web page from the MobilePage base class and add mobile Web server controls from the System.Web.Mobile namespace. Mobile Web server controls have a number of specialized adapters in the .NET

Framework and are therefore especially geared to developing mobile Web applications that target a wide range of mobile devices.

C. ASP.NET Web Server Controls and the Adapter Architecture

Most ASP.NET 2.0 Web server controls adhere to the unified adapter architecture. This means that all controls can behave differently depending on the requesting device by calling a custom adapter that provides appropriate behaviors for that device, such as creating the proper markup language. If an adapter is configured in the browser definitions file for the requesting device or browser, ASP.NET calls the adapter at each life-cycle stage of a Web server control. The adapter can then adjust rendered output for example, and handle any device-specific view state logic or device idiosyncrasies. Browser definition files can be found in the Browsers folder of the .NET Framework Config directory or in the App_Browsers folder of a Web application. There are currently no adapters provided for the ASP.NET controls. There are, however, a rich set of adapters for the ASP.NET mobile controls to provide for a wide variety of devices and browsers. You can create custom adapters for each device and have the ASP.NET page framework use those adapters when a specific device accesses your page.


Choosing Custom Adapters or Mobile Controls

For pages targeting mobile devices, mobile Web server controls are used and pages are inherited from MobilePage. These controls support many mobile devices, such as cell phones. ASP.NET includes mobile Web server controls for a wide variety of general Web development and mobile-specific needs. Additionally, mobile-control device adapters already exist for major devices and their markup languages. Microsoft will continue to provide adapter updates for the mobile Web server controls when major markup languages evolve. This enables you to support new markup languages with the same controls that you are already using. For example, if we are creating an e-commerce site that supports desktop browsers as well as a large array of mobile devices, we would create a set of ASP.NET pages that inherit from the Page class, and a separate set of pages that inherit from the MobilePage base class and use mobile controls. There are scenarios where using ASP.NET Web server controls and writing custom adapters makes sense. These typically will be applications for rich desktop browsers where browser behavior variations are required, or for applications to be targeted by a constrained device class for which mobile controls and their feature set is not warranted.

Since ASP.NET Web Forms and MVC are both primarily server-side technologies, this white paper will focus on server-side techniques that help produce different markup and logic for mobile browsers. This server side Technique can be combined with any

client-side technique (e.g., CSS 3 media queries, progressive-enhancement JavaScript), but thats more a matter of web design than ASP.NET development.

5. Browser and Device Detection

The key prerequisite for all server-side techniques for supporting mobile devices is to know what device your visitor is using. In fact, even better than knowing the manufacturer and model number of that device is knowing the characteristics of the device. Characteristics may include: Is it a mobile device? Input method (mouse/keyboard, touch, keypad, joystick, ) Screen size (physically and in pixels) Supported media and data formats.

Its better to make decisions based on characteristics than model number, because then youll be better equipped to handle future devices. ASP.NET Web Forms and MVC developers can immediately discover important characteristics of a visiting browser by inspecting properties of the Request.Browser object. For example, Request.Browser.IsMobileDevice Request.Browser.MobileDeviceManufacturer, Request.Browser.MobileDeviceModel Request.Browser.ScreenPixelsWidth Request.Browser.SupportsXmlHttp etc.

Behind the scenes, the ASP.NET platform matches the incoming User-Agent (UA) HTTP header against regular expressions in a set of Browser Definition XML files. By default the platform includes definitions for many common mobile devices, and we can add custom Browser Definition files for others that wish to be recognize.

6. Creating a Mobile Application i. Creating a mobile-specific master page

Depending on the requirements, you may be able to use the same Web Forms for all visitors, but have two separate master pages: one for desktop visitors, another for mobile visitors. This gives you the flexibility of changing the CSS stylesheet or your top-level HTML markup to suit mobile devices, without forcing you to duplicate any page logic. This is easy to do. For example, you can add a PreInit handler such as the following to a Web Form: protected void Page_PreInit(object sender, EventArgs e) { if (Request.Browser.IsMobileDevice) MasterPageFile = "/Mobile.Master"; }

Now, create a master page called Mobile.Master in the top-level folder of your application, and it will be used when a mobile device is detected. Your mobile master page can reference a mobile-specific CSS stylesheet if necessary. Desktop visitors will still see your default master page, not the mobile one.


Creating independent mobile-specific Web Forms

For maximum flexibility, you can go much further than just having separate master pages for different device types. You can implement two totally separate sets of Web Forms pages one set for desktop browsers, another set for mobiles. This works best if you want to present very different information or workflows to mobile visitors. The rest of this section describes this approach in detail. For this the easiest way to proceed is to create a subfolder called Mobile within the project, and builds mobile pages there. Construct an entire sub-site, with its own master pages, style sheets, and pages, using all the same techniques that are used for any other Web Forms application. Its not necessary to produce a mobile equivalent for everypage in desktop site; we can choose whatever subset of functionality makes sense for mobile visitors. These mobile pages can share common static resources (such as images, JavaScript, or CSS files) . Since the Mobile folder will not be marked as a separate application when hosted in IIS (its just a simple subfolder of Web Forms pages), it will also share all the same configuration, Session data, and other infrastructure as the desktop pages. Note: Since this approach usually involves some duplication of code (mobile pages are likely to share some similarities with desktop pages), its important to factor out any common business logic or data access code into a shared underlying layer or service.


Redirecting mobile visitors to mobile pages

Its often convenient to redirect mobile visitors to the mobile pages only on the first request in their browsing session (and not on every request in their session), because:

Mobile visitors can get access to desktop pages if they wish just put a link on your master page that goes to Desktop version. The visitor wont be redirected back to a mobile page, because its no longer the first request in their session. It avoids the risk of interfering with requests for any dynamic resources shared between desktop and mobile parts of your site (e.g., if we have a common Web Form that both desktop and mobile parts of your site display in an IFRAME, or certain Ajax handlers)

To do this, redirection logic can be placed in a Session_Start method. For example, add the following method to your Global.asax.cs file: void Session_Start(object sender, EventArgs e) { // Redirect mobile users to the mobile home page HttpRequest httpRequest = HttpContext.Current.Request; if (httpRequest.Browser.IsMobileDevice) { string path = httpRequest.Url.PathAndQuery;

bool isOnMobilePage = path.StartsWith("/Mobile/", StringComparison.OrdinalIgnoreCase); if (!isOnMobilePage) { string redirectTo = "/Mobile/"; // // // // // } Could also add special logic to redirect from certain recognized pages to the mobile equivalents of those pages (where they exist). For example, if (HttpContext.Current.Handler is UserRegistration) redirectTo = "/Mobile/Register.aspx";

HttpContext.Current.Response.Redirect(redirectTo); } }


Configuring Forms Authentication to respect your mobile pages

Note that Forms Authentication makes certain assumptions about where it can redirect visitors during and after the authentication process:

When a user needs to be authenticated, Forms Authentication will redirect them to desktop login page, regardless of whether theyre a desktop or mobile user (because it only has a concept of one login URL). Assuming we want to style your mobile login page differently, you need to enhance our desktop login page so that it redirects mobile users to a separate mobile login page. For example,we add the following code to your desktop login page code-behind:
public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Ensure that if Forms Authentication forces a mobile user // to log in, we display the mobile login page string returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl) && returnUrl.StartsWith("/Mobile/", StringComparison.OrdinalIgnoreCase)) { Response.Redirect("/Mobile/Account/Login.aspx?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl)); } RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } }

After a user successfully logs in, Forms Authentication will by default redirect them to your desktop home page (because it only has a concept of one default page). We need to enhance the mobile login page so that it redirects to the mobile home page after a successful log-in. For example,we can add the following code to your mobile login page code-behind:
public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Ensure that after logging in, mobile users stay on mobile pages string returnUrl = Request.QueryString["ReturnUrl"]; if (String.IsNullOrEmpty(returnUrl)) { returnUrl = "/Mobile/";

} LoginUser.DestinationPageUrl = returnUrl; // (the following line is already present by default) RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } }

This code assumes that page has a Login server control called LoginUser, as in the default project template.


Working with Output Caching

If output caching is being, beware that by default its possible for a desktop user to visit a certain URL (causing its output to be cached), followed by a mobile user who then receives the cached desktop output. This warning applies whether were just varying your master page by device type, or implementing totally separate Web Forms per device type. To avoid the problem, we can instruct ASP.NET to vary the cache entry according to whether the visitor is using a mobile device. Add a VaryByCustom parameter to the pages OutputCache declaration as follows: <%@ OutputCache VaryByParam="*" Duration="60" VaryByCustom="isMobileDevice" %> Next, define isMobileDevice as a custom cache parameter by adding the following method override to your Global.asax.cs file: public override string GetVaryByCustomString(HttpContext context, string custom) { if (string.Equals(custom, "isMobileDevice", StringComparison.OrdinalIgnoreCase)) return context.Request.Browser.IsMobileDevice.ToString(); return base.GetVaryByCustomString(context, custom); } This will ensure that mobile visitors to the page dont receive output previously put into the cache by a desktop visitor.


Setting up a Mobile area within your ASP.NET MVC application

We can add an area called Mobile to an existing ASP.NET MVC application in the normal way: right-click on your project name in Solution Explorer, then choose Add Area. Then add controllers and views as for any other area within an ASP.NET MVC application.


Ensuring the URL /Mobile reaches the mobile homepage

If we want the URL /Mobile to reach the Index action on HomeController inside the Mobile area, we will need to make two small changes to our routing configuration. First, update the MobileAreaRegistration class so that HomeController is the default controller in the Mobile area, as shown in the following code: public override void RegisterArea(AreaRegistrationContext context) { // By default there is no "controller" parameter in the following line. // Add one referencing "Home" as shown. context.MapRoute( "Mobile_default", "Mobile/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } This means the mobile homepage will now be located at /Mobile, rather than /Mobile/Home, because Home is now the implicitly default controller name for mobile pages. Next, note that by adding a second HomeController to the application (i.e., the mobile one, in addition to the existing desktop one), the regular desktop homepage is broken. It will fail with the error Multiple types were found that match the controller named 'Home'. To resolve this, update your top-level routing configuration (in Global.asax.cs) to specify that the desktop HomeController should take priority when theres ambiguity: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, ); } Now the error will go away, and the URL http://yoursite/ will reach the desktop homepage, and http://yoursite/mobile/ will reach the mobile homepage. // Add the namespace of your desktop controllers here new[] { "YourApplication.Controllers" }


Redirecting mobile visitors to your mobile area

There are many different extensibility points in ASP.NET MVC, so there are many possible ways to inject redirection logic. One neat option is to create a filter attribute, [RedirectMobileDevicesToMobileArea], that performs a redirection if the following conditions are met: 1. Its the first request in the users session (i.e., Session.IsNewSession equals true) 2. The request comes from a mobile browser (i.e., Request.Browser.IsMobileDevice equals true) 3. The user is not already requesting a resource in the mobile area (i.e., the path part of the URL does not begin with /Mobile)

As its a filter, we can choose either to apply it to specific controllers and actions, e.g., public class HomeController : Controller { [RedirectMobileDevicesToMobileArea] // Applies just to this action public ActionResult Index() { // ... } } or can apply it to all controllers and actions as an MVC 3 global filter in the Global.asax.cs file: protected void Application_Start() { // (rest of method unchanged) // Using "order" value 1 means it will run after unordered filters // associated with specific controllers or actions, so the redirection // location can be overridden for specific actions GlobalFilters.Filters.Add(new RedirectMobileDevicesToMobileAreaAttribute(),

1); }

The subclasses of this attribute that redirect to specific locations within the mobile area can be created. This means, for example, we can: Register a global filter as shown above that sends mobile visitors to the mobile homepage by default. Also apply a special [RedirectMobileDevicesToMobileProductPage] filter to a view product action that takes mobile visitors to the mobile version of whatever product page they had requested. Also apply other special subclasses of the filter to specific actions, redirecting mobile visitors to the equivalent mobile page.


Configuring Forms Authentication to respect your mobile pages

In Forms Authentication, when a user needs to log in, it automatically redirects the user to a single specific log on URL, which by default is /Account/LogOn. This means that mobile users may be redirected to your desktop log on action. To avoid this problem, we add logic to the desktop log on action so that it redirects mobile users again to a mobile log on action. If we are using the default ASP.NET MVC application template, update AccountControllers LogOn action as follows: public ActionResult LogOn() { string returnUrl = Request.QueryString["ReturnUrl"]; if ((returnUrl != null) && returnUrl.StartsWith("/Mobile/", StringComparison.OrdinalIgnoreCase)) { return RedirectToAction("LogOn", "Account", new { Area = "Mobile", ReturnUrl = returnUrl });

} return View();

and then implement a suitable mobile-specific log on action on a controller called AccountController in the Mobile area.


Styling mobile pages for mobile browsers

Its beyond the scope of this document to describe in great detail what kinds of HTML markup work correctly or which web design techniques maximize usability on particular devices. Its up to the developer to find a sufficiently simple layout, optimized for a mobile-sized screen, without using unreliable HTML or CSS positioning tricks. One important technique worth mentioning, however, is the viewport meta tag. Certain modern mobile browsers, in an effort display web pages meant for desktop monitors, render the page on a virtual canvas, also called viewport (e.g., the virtual viewport is 980 pixels wide on iPhone, and 850 pixels wide on Opera Mobile by default) and then scale the result down to fit onto the screens physical pixels. The user can then zoom in and pan around that viewport. This has the advantage that it lets the browser display the page in its intended layout, but its also has the disadvantage that it forces zooming and panning, which is inconvenient for the user. If youre designing for mobile, its better to design for a narrow screen so that no zooming or horizontal scrolling is necessary. A way to tell the mobile browser how wide the viewport should be is through the nonstandard viewport meta tag. For example, if you add the following to your pages HEAD section, <meta name="viewport" content="width=480"> then supporting smartphone browsers will lay out the page on a 480-pixel wide virtual canvas. This means that if the HTML elements define their widths in percentage terms, the percentages will be interpreted with respect to this 480-pixel width, not the default viewport width. As a result, the user is less likely to have to zoom and pan horizontally considerably improving the mobile browsing experience. If we want the viewport width to match the devices physical pixels, we can specify the following: <meta name="viewport" content="width=device-width"> For this to work correctly, we must not explicitly force elements to exceed that width (e.g., using a widthattribute or CSS property), otherwise the browser will be forced to use a larger viewport regardless. Most modern smartphones support dual orientation: they can be held in either portrait or landscape mode. So, its important not to make assumptions about the screen width in pixels. Dont even assume that the screen width is fixed, because the user can re-orient their device while they are on your page.


How ASP.NET MVC applications can present mobilespecific pages

Since the Model-View-Controller pattern decouples application logic (in controllers) from presentation logic (in views), Any of the following approaches to handling mobile support in serverside code can be used:

1. Use the same controllers and views for both desktop and mobile browsers, but

render the views with different Razor layouts depending on the device type. This option works best if youre displaying identical data on all devices, but simply want to supply different CSS stylesheets or change a few top-level HTML elements for mobiles. 2. Use the same controllers for both desktop and mobile browsers, but render different views depending on the device type. This option works best if youre displaying roughly the same data and providing the same workflows for end users, but want to render very different HTML markup to suit the device being used. 3. Create separate areas for desktop and mobile browsers, implementing independent controllers and views for each.This option works best if youre displaying very different screens, containing different information and leading the user through different workflows optimized for their device type. It may mean some repetition of code, but you can minimize that by factoring out common logic into an underlying layer or service. If we want to take the first option and vary only the Razor layout per device type, its very easy. Just modify the _ViewStart.cshtml file as follows: @{ Layout = Request.Browser.IsMobileDevice ? "/Views/Shared/_LayoutMobile.cshtml" : "/Views/Shared/_Layout.cshtml"; } Now we can create a mobile-specific layout called _LayoutMobile.cshtml with a page structure and CSS rules optimized for mobile devices. If we want to take the second option render totally different views according to the visitors device type. The third option creating separate controllers and views for mobile devices so you can control exactly what subset of functionality is offered for mobile visitors has already been defined in the Preceeding sections.