ASP.NET Mobile Controls


HTML and WML are similar markup languages, more or less like Italian and Spanish. As an Italian, you could grab the sense of what Spanish speaking people are saying, but if you need to write correct Spanish, then that's a totally different story.
-Luca Passani, Openwave

Years ago, one of the factors for the rapid adoption of ASP was the level of programmability it added on top of HTML. Not only could you apply some business logic to generate appropriate HTML tags, you could also straighten out the differences between the browsers. The overall architecture has been redesigned and empowered with ASP.NET, which provides a thicker abstraction layer and a richer object model fully integrated with the .NET Framework. In addition, ASP.NET 1.1 incorporates mobile controls. Mobile controls provide an abstracted programming model to build wireless Web applications. ASP.NET mobile controls are a revised version of the Microsoft Mobile Internet Toolkit (MMIT)—the SDK for mobile wireless devices. An integral part of the .NET Framework 1.1, the MMIT is available as a separate download for the .NET Framework version 1.0.

ASP.NET mobile controls enable you to build Web applications for wireless devices using the same rich application model that characterizes development for desktop browsers. Mobile controls target a variety of devices such as cell phones, pagers, the Pocket PC, and other personal digital assistants (PDA) such as Palm and BlackBerry devices. ASP.NET mobile controls extend the Web Forms model of ASP.NET in two ways—devices and ad hoc controls. All supported devices are listed in a new section of the machine.config file (discussed in Chapter 12, "Configuration and Deployment"). It's an extensible list open to the contribution of third parties, who can register new devices as well as new controls.

Registering a new device mostly means providing a list of characteristics (for example, screen size or markup language), and then one of the built-in adapters can be used by the .NET Framework to generate device-specific output. Less frequently, you need to write a new adapter too. You don't need to call into the adapter or manually write device-specific code; instead, you simply write mobile applications using the ASP.NET mobile controls and the ASP.NET object model. Based on the configuration information, Mobile Web Forms detect the underlying device and adaptively renders the output of controls by using the specific markup language and logic. ASP.NET mobile controls abstract a subset of ASP.NET server controls and intelligently render your application on the target device. In addition, several mobile-specific controls are provided, such as the PhoneCall control. The .NET Framework 1.1 provides a handful of built-in controls but remains open to third-party contributions.

Mobile Web applications can be developed using the Mobile Designer in Microsoft Visual Studio .NET as well as any other editor, such as Web Matrix or Notepad. Because ASP.NET mobile applications are .NET applications, you can develop them using any common language runtime (CLR)–compliant programming language.

In this chapter, we'll provide an overview of the ASP.NET mobile controls, discuss the basics of the mobile technology, and take a quick tour of the Visual Studio .NET mobile features.

Architecture of Mobile Controls

ASP.NET mobile controls are an extension of ASP.NET desktop server controls. Another way of characterizing mobile controls is to say they are the twin brother of desktop controls. Mobile controls add the capability of adapting to the device that is making the request. Automatic browser detection is a key aspect of mobile applications and controls and is probably a bit more important for them than for desktop controls.

Desktop controls are rendered in different modes to accommodate a few client targets (for example, Internet Explorer 5.0, HTML 3.2, and HTML 4.0). Although the final output can vary a lot from one target to the next, the area of markup most affected is style. Validation controls are controls whose output varies significantly from one target browser to another. Desktop server controls always generate HTML code. Although differences exist between the HTML 3.2 and HTML 4.0 standards, and between standards and the implementations of individual browsers, we're still far from the untangled mess of dialects and syntaxes that characterize the markup in the mobile world. For this reason, browser detection is implemented at a lower level than user code. Basically, the ASP.NET mobile runtime evaluates the browser's user agent and selects the appropriate device adapter object to use for any task that involves the request. (A user agent is a request header that contains information about the capabilities of the browser.) As a result, any mobile controls conform to the capabilities of the particular device it is running on.

The set of supported wireless devices is rather heterogeneous and ranges from full-featured browsers found on PDAs to small cell phone displays featuring WML browsers. As a result, not just the markup output but also the design of the application might significantly change from one device to the next. In general, a multiauthoring tool for mobile controls must abstract a number of aspects: different markup languages, vendor-specific implementations of the same markup, and different form factors (such as display size and programmable buttons). ASP.NET mobile controls internally handle much of the boring device-specific rendering and let you focus on the Web-application logic.

Multiple Markup Languages

ASP.NET mobile controls support a few types of markup languages, which are listed in Table 11-1. Acceptable values don't include all possible wireless markup languages, but they certainly include the most popular ones.

Table 11-1: Markup Languages in ASP.NET Mobile Controls



Compact HTML 1.0

Subset of HTML 3.2, has been specifically designed for mobile phones and in general for battery-powered, low-memory devices. Abbreviated as cHTML. The language is widely used in Japanese I-Mode devices.

HTML 3.2

Relatively old version of HTML, is supported by high- end PDAs such as Pocket PC 2002, Palm, and BlackBerry devices.

WML 1.1, WML 1.2

The Wireless Markup Language (WML) is probably the most popular wireless language. It has been developed as a part of a larger initiative aimed at defining an application protocol for wireless devices—the Wireless Application Protocol (WAP). WML lets you program the keys of a mobile phone, such as softkeys and the numeric pad.


XHTML is the XML reformulation of HTML and a key element of the WAP 2.0 standard. There are several flavors of XHTML out there. The Device Update 2.0 of ASP.NET Mobile Controls supports XHTML Mobile Profile. It is available for download at

The list has a couple of noticeable omissions—the Handheld Device Markup Language (HDML) and the newest version 1.3 of the Wireless Markup Language (WML). However, be aware that new devices—and possibly even new markup languages—can be added to the list of supported devices at any time.

The required markup language that the controls should generate is set through a read-only string property in the MobileCapabilities class—PreferredRenderingType.

Compact HTML

As the name implies, Compact HTML (cHTML) is a simplified version of HTML developed for less powerful browsers embedded in cell phones and other small- screen devices. The cHTML language consists of a mix of HTML 2.0 and HTML 3.2 tags optimized for navigation and text display.

The cHTML language supports hyperlinks, text scrolling, forms, and data submission. It doesn't provide much layout and formatting capabilities because of the rather spartan user interface (UI) of such devices. So tables, frames, cascading style sheets (CSS), fonts, and scripting are not supported. Just the lack of scripting support in cHTML provides a prime example of the great job done by ASP.NET device adapters. Adapters force the exclusive generation of server-side code for data validation, and they always implement postback events through a form's data submission. For more information on cHTML, take a look at


The cHTML markup language is mostly used in Japan by I-Mode devices, although some experiments have been made in Europe, particularly in the Netherlands. Some browsers—specifically the newest Openwave XHTML browser—support cHTML internally to access I-Mode sites.

HTML 3.2

HTML 3.2 is a more basic version of HTML, whose latest version is numbered 4.0. HTML 3.2 is the markup language for most down-level browsers, such as Netscape Navigator 3.x. HTML 3.2 is also supported in Pocket Internet Explorer. Key differences between HTML 4.0 and 3.2 include the addition of cascading style sheets and the Dynamic HTML (DHTML) object model. In general, targeting HTML 3.2 is fair for many ASP.NET applications and doesn't constitute a restriction in the overall functionality. The HTML 3.2 specification is available at

Wireless Markup Language

Historically speaking, the WML language was the standard markup language that emerged as the result of joint efforts to standardize one proprietary language—the HDML. Created through an initiative of the WAP Forum (now renamed to Open Mobile Alliance, and which can be found at, the WML language is founded on a strict XML syntax and shares only a few tags with HTML. Some examples of the shared tags are , , , , and . However, even in the context of the same tag (for example, ), the intended behavior might be different. WML tags are case-sensitive, while HTML tags are not.

On a more technical note, WML pushes the idea of cards, which represent the various states of the application. A card is like a wizard page, and most of the application's life is spent navigating between cards. In addition, WML supports a form of exception handling to catch errors that occur in a card.

The Wireless Application Protocol

A key point with the mobile controls is that you don't need to worry about the markup language or transport mechanism used for the request. However, learning a little more about the WAP protocol is helpful anyway. The WML language was developed as part of a wider initiative aimed at ruling the world of wireless development. The WAP Forum was started in 1997 with the declared goal of defining the technologies that would unify the world of wireless applications. WAP is a suite of wireless-specific specifications adapted from open Web standards such as HTML and TCP/IP.

To access a Web site using a mobile device, you type the URL in the mobile browser and have the browser create an HTTP-like request (which can optionally be encrypted) that travels toward the back-end Web server over the Wireless Session Protocol (WSP). The WSP protocol uses packets whose overall semantics are similar to HTTP packets. Unlike HTTP, though, WSP transfers binary packets to save bandwidth. WSP packets are physically transported by the Wireless Transaction Protocol (WTP), the wireless counterpart of TCP, as shown in Figure 11-1.

click to expand
Figure 11-1: Architecture of wireless Web applications.

The connection between the mobile device and the WAP gateway can be secured using the Wireless Transport Layer Security (WTLS) protocol. The WAP gateway is a server that translates the WSP request into conventional HTTP and forwards it to the back-end Web server.


The Open Mobile Alliance released the WAP 2.0 standard in September 2001. Although 100 percent backward compatibility is guaranteed, the new standard is geared toward a full convergence between the wireless Web and the conventional HTTP-based Web. The WAP 2.0 standard is heavily based on XHTML and brings the power of CSS to the wireless world by introducing WCSS, which is an abridged version of Web CSS for wireless devices.

The Web server receives the request and performs any needed operations. The returned output is an HTTP response that contains a WML document. After receiving the WML stream, the gateway removes any unneeded headers and translates it into binary packets. The response is then forwarded back to the device and displayed. (Actually, the WML-to-binary translation consists of a simple tokenization in which each tag and attribute is mapped to a single byte.)

Overview of Mobile Controls

ASP.NET mobile controls are server controls and thus require their runat attribute to be set to server. They execute on the server and for this reason can exploit the potential of the .NET Framework in spite of the modest amount of memory typically available on wireless devices. All mobile controls inherit from the MobileControl base class, which in turn inherits from Control. In this relationship, both server and mobile controls share a common set of properties, methods, and events. Mobile Web forms, on the other hand, inherit from the MobilePage class. Later in the chapter, we'll write a sample mobile application using Visual Studio .NET. In the meantime, let's learn more about the hierarchy of mobile controls and their internal plumbing.

Mobile Controls Hierarchy

ASP.NET mobile controls can be logically grouped in five categories: container, text, validation, list, and miscellaneous controls. Table 11-2 lists them all in alphabetical order. Some of these controls work in much the same way as ASP.NET Web Forms controls do. However, mobile controls also provide adaptive rendering for mobile devices. We'll discuss adaptive rendering more later in the "Adaptive Rendering" section.

Table 11-2: ASP.NET Mobile Controls

Mobile Control



Provides advertisement rotation in the same way that the ASP.NET AdRotator control does.


Provides date-picking functionality mimicking the behavior of the ASP.NET Calendar control.


Similar to the ASP.NET Button control, causes a postback event after users click.


Identical to the ASP.NET CompareValidator control.


Identical to the ASP.NET CustomValidator control.


The control is similar to the HtmlForm control of ASP.NET pages. However, multiple form controls are admitted on mobile pages.


Identical to the ASP.NET Image control.


Identical to the ASP.NET Label control.


Represents a hyperlink to another form on a mobile page or an arbitrary URL. Similar to the ASP.NET HyperLink control.


Similar to the ASP.NET Repeater and DataList controls, applies templates to bound data. Supports device-specific templates.


Similar to the ASP.NET DataGrid control, displays multiple fields for each data item and supports multiple commands.


Provides grouping mechanism for organizing controls in much the way the ASP.NET Panel control does.


For devices that support phone calls, the control represents a link to a phone number to call. Similar to the mailto tag of HTML hyperlinks.


Identical to the ASP.NET RangeValidator control.


Identical to the ASP.NET RegularExpressionValidator control.


Identical to the ASP.NET RequiredFieldValidator control.


Displays a list of data-bound items with different styles. It can be configured to behave like a drop- down or check-box list. Selection, however, does not automatically cause the control to post back. The change of selection, though, will fire a server event with the next postback.


Invisible control, can be used to organize styles to apply to other controls. Can contain multiple style definitions.


Represents a single-line text-box control. Does not support read-only and multiline.


Used to display large blocks of text, supports basic text formatting and pagination.


Similar to the ValidationSummary control of ASP.NET, displays the results of the validation in a separate form.

Almost all mobile controls have a counterpart in the family of ASP.NET server controls or, at a minimum, a control that looks alike. PhoneCall and TextView are the only two without an equivalent control. Other controls, such as SelectionList and Command, group the functionality of multiple ASP.NET controls. The programming interface of validation controls, on the other hand, is nearly identical to ASP.NET; a key difference here is that not all devices support client-side validation. Figure 11-2 shows graphically the relationships between controls. Controls with a white background are abstract classes.

click to expand
Figure 11-2: The ASP.NET mobile control class hierarchy.

Before taking a closer look at the characteristics of each group of controls, let's learn more about the structure of an ASP.NET mobile page.

ASP NET Mobile Pages

The MobilePage class is the base class for all ASP.NET mobile Web pages and inherits from the ASP.NET Page class. In other words, a mobile page is in no way different from a user-defined page class such as a code-behind class. An .aspx page that intends to use ASP.NET mobile controls must declare its base class by using the Inherits attribute on the @Page directive.

<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" %>

In addition, all mobile controls are perceived as custom controls and must be explicitly registered in all pages. As we saw in the previous chapter, this can be done using the @Register directive.

<%@ Register TagPrefix="mobile"
 Assembly="System.Web.Mobile" %>

The prefix mobile, although extremely intuitive, is totally arbitrary and can be replaced with any other string. You should note, though, that the whole documentation of ASP.NET mobile controls uses the prefix mobile. If you're authoring the page using Visual Studio .NET, using the prefix mobile is mandatory. In fact, once a mobile project has been set up, Visual Studio .NET defaults to mobile and doesn't recognize any new prefix. As a result, either you manually update the prefix each time you drop a new control on the designer or the page won't compile!

The following listing shows a simple page that displays the name of the wireless language being used by the device:

<%@ Page Language="C#" 
 Inherits="System.Web.UI.MobileControls.MobilePage" %>
<%@ Register TagPrefix="mobile"
 Assembly="System.Web.Mobile" %>
<%@ Import Namespace="System.Web.Mobile" %>

 Language is 

The page contains a Label control that renders with boldface type and some literal text. During the page OnLoad event, the code retrieves the preferred rendering type from the requesting device, reads related settings from the configuration file, and displays it. The MobileCapabilities class is defined in the System.Web.Mobile namespace; the controls, on the other hand, are all defined in the System.Web.UI.MobileControls namespace. When viewed through a device that incorporates the Openwave browser, the page looks like the one shown in Figure 11-3.

click to expand
Figure 11-3: The first mobile application in action as seen through the Openwave emulator.


The mobile samples in this chapter were tested with the Openwave emulator included with the Openwave SDK version 4.1.1. This SDK is free of charge and can be downloaded from Openwave ( Not all emulators are supported by the ASP.NET mobile controls. For a list of emulators to test your mobile applications, check out /DeviceSimulators.aspx. For a list of tested devices and emulators, check out

The mobile page detected the device capabilities and generated the following WML 1.1 output:


Language is wml11

Interestingly, the same page is also viewable through Internet Explorer. In this case, the target language is HTML 3.2. Figure 11-4 shows the Internet Explorer version of the page.

click to expand
Figure 11-4: The same mobile application rendered by Internet Explorer.

In this case, the output sent to the device is completely different.


Language is html32


A variety of emulators exist to test the interface of a mobile application at development time. Although you should never ship a wireless application without first seriously testing it on real devices, emulators are indeed extremely helpful to prototype the user interface. Visual Studio .NET lets you register browsers for mobile applications by selecting Browse With from the File menu.

A MobilePage object can contain only a Form or StyleSheet control. Literal text placed outside a form is ignored. If other controls are used outside the boundaries of a form, a compiler error is raised. All needed text and controls must always be placed within a form. A mobile page must contain at least one form; multiple forms are supported, but only one is visible at a time. A style sheet is not required for a mobile page. However, you can't indicate more than one style sheet per page.

Pagination in Mobile Pages

ASP.NET mobile controls provide a mechanism for automatically partitioning the form's contents into smaller portions of markup code. This mechanism is known as pagination. When you use pagination, these segments of content are automatically formatted to fit the target device. The final output is also completed with common user- interface elements that you can use to browse to other pages.

By default, pagination is not activated for a form. To activate pagination, you must set the Paginate property of the Form to true. You should note that although pagination can be enabled on individual controls, the setting has no effect if the Paginate property of the containing form is set to false. The Form control also provides other properties—such as PageCount, CurrentPage, and PagerStyle—that allow you to control pagination behavior. You can also specify pagination for a particular control on a form by using the ControlToPaginate property of the form with the ID of the control.

The main motivation for pagination is to not exceed the memory capabilities of the device with a too large page. Pagination is particularly effective for controls that display large amounts of data; it's often redundant for forms that display interactive and input controls. The pagination is implemented by sectioning the structure of the form or the control into pieces. Some controls (for example, the List control) handle pagination internally and decide themselves how to break their output. Other controls are managed by the container controls; to be effectively pageable, they must contain child controls or fit entirely in a single page.

The Life Cycle of a Mobile Page

The life cycle of an ASP.NET mobile page is nearly identical to the life cycle of a conventional Web Forms page. The events are the same, even though the system's behaviors before and after the various events are different. The phases in the cycle are summarized as follows:

  • Page initialization At this phase, the page determines the device adapter to use and sets the Adapter property on the MobilePage class. The device adapter is an instance of one of the classes listed in the section of the configuration files. Default adapters are registered in machine.config; in web.config, you could add application-specific adapters. The search for the adapter begins with the machine.config file and then proceeds to the root web.config and any innermost web.config that might have been defined. The adapter is picked up based on the detected characteristics of the underlying device. Note that the adapter is cached for performance so that the search is conducted only once per user agent. The event you can hook up at this time is the Init event both on the page and the adapter.
  • Loading the view state During this phase, any saved state for the page is restored. There is no event associated with this phase. Gaining more control over this phase requires the override of the LoadViewState method of the page.
  • Loading postback data The page loads all incoming

    data cached in Request and updates the page properties accordingly. No user event is associated with this phase. Gaining more control over this phase requires the override of the LoadPostData method of the page.
  • Loading the user code The page is ready to execute any initialization code related to the logic and behavior of the page. The page fires the Load event and performs device adapter–specific loading of information. To control this phase, you can handle the Load event both on the page and the adapter.
  • Send postback change notifications Controls in the page raise change events in response to state changes between the current and previous postbacks. Any further change entered by the Load event handler is also taken into account to determine any difference. A control must implement the IPostBackDataHandler interface to get a chance from the page to fire a state change event during this phase. No user event is provided.
  • Handle postback events The page executes the .aspx code associated with the client-side event that caused the postback. It's the heart of the ASP.NET Web Forms model.
  • Pre-rendering The code can perform its last updates before the output is rendered. The event developers can hook up from a mobile page or the device adapter at this phase is PreRender. Pagination occurs at this time. During this phase, the output of the page is determined based on the pagination settings.
  • Saving the view state During this phase, the page serializes its state to a string, which will then be persisted—typically, through a hidden field. No user event is associated with this phase.
  • Page rendering The page generates the output to be rendered to the client. The adapter is responsible for accessing and rendering child controls in the appropriate order. The event is Render and is available on both the page object and the device adapter.
  • Page unload This phase performs the device adapter–specific cleanup and unloading. The event is Unload and is available on both the page object and the device adapter.

In summary, mobile pages differ from conventional ASP.NET pages in particular because of the initialization step. At that phase, in fact, mobile pages and controls have to determine the device adapter to use from the list of registered objects. The adapter is exposed through the Adapter property, and pages and controls refer to it for rendering.

Device Adapters

Although the programmer writes ASP.NET mobile applications in a device-independent fashion, a set of device adapters take care of translating the high-level description of a user interface into the device-specific presentation layer. Interesting analogies exist between device drivers in Microsoft Windows and device adapters in ASP.NET mobile controls. Both control a device by generating device-specific command text; device adapters just generate that in the form of markup languages. Device adapters are the bridge between individual mobile controls and target devices. For any given device, each mobile control can have a unique adapter and each instance of a control is bound to a corresponding instance of an adapter. The availability of an adapter is critical for the appropriate rendering of mobile controls. In general, for each supported device, the following classes can be defined:

  • Page adapter Associated with the page, this class provides view-state and postback functionality, as well as methods that save and load device-specific control-state information, such as pagination information and the currently active form. The page adapter is also responsible for preparing the response to the client and for rendering the skeleton of the page. The page adapter class implements the IPageAdapter interface.
  • Form adapter Associated with the form control, this adapter provides methods that handle device- specific form-based interactivity. In addition, it should supply methods that adapt a generic form to the particular device. For example, the fields of the forms could be paginated or grouped into a menu. Finally, the form adapter must be able to render the skeleton of the form.
  • Control adapter This is the base class for control adapters and is also the base class for page and form adapters. It provides methods for rendering control postback events and style properties.
  • Text writer The text writer class is not an adapter class, but it works in conjunction with adapters. The text writer class inherits from the HtmlTextWriter class and performs all rendering for a control. An instance of the text writer class is created and passed through every adapter for rendering purposes. The text writer usually contains helper methods to perform tasks such as encoding data.

The ASP.NET Mobile Controls toolkit contains a few device adapters, one for each supported markup language—cHTML, XHTML, HTML, and WML. As mentioned, XHTML has been added to the list in the Device Update 2.0.

Container Controls

ASP.NET mobile controls include a couple of controls—Panel and Form—that act as containers of other controls. The Form control differs from Panel in that it supports posting of data, whereas the Panel represents a simple static group of related controls. Multiple panels can be nested and included in forms; forms, on the other hand, cannot be nested.

The Panel Control

The following code demonstrates a couple of panels containing plain text with minimal formatting. Note that not all attributes are supported on all devices. For example, background and foreground colors are ignored by cell phones.

 Programming ASP.NET
 Dino Esposito

A panel can contain any ASP.NET mobile control other than MobilePage, Form, or StyleSheet controls. Panel controls do not have a visual representation and cascade any style properties down to the individual controls. Both the layout and style of the child controls are mediated by the device adapter.

Note that the Panel control could be used to define pagination segments. In addition, a Panel control can also work as a sort of placeholder to contain dynamically generated child controls.

The Form Control

The Form control represents the outermost container of controls within a mobile page. The Form control features common-use properties such as Action and Method. In particular, Action defaults to the empty string, which causes a postback to the same URL. A form fires events when activated and deactivated.

A page can contain multiple forms, but only one form is rendered to the browser at a time. The currently active form can be set and retrieved through the ActiveForm property. When multiple forms are active on the same page, you can move from one to the other by using a Link control.


To make a Link control point to an internal form, you set the NavigateURL property to the ID of the form prefixed with a # symbol.

List Controls

The List, ObjectList, and SelectionList controls are the mobile counterpart of ASP.NET list-bound and iterative controls. The List control looks like the Repeater and the DataList, and it displays a static or bound list of items. The SelectionList is helpful if you need the user to pick one or more items from a list. Finally, you should use the ObjectList control if you need to display database information in a tabular format. Note that the ObjectList control is strictly data-bound, while the other two can also display a list of items set either statically or programmatically.

The List Control

As mentioned, a List control renders a sequence of items to a device. The control can work in static or interactive mode. In static mode, the control generates a static list in which each item is plain text. In interactive mode, all items are rendered as clickable elements that generate an event if clicked. If an event handler for the ItemCommand event is present, the control works interactively; otherwise, it appears as a static option list. When set to true, the ItemsAsLinks property transforms the list items into hyperlinks. In this case, no ItemCommand event will ever be fired because the click is resolved by jumping to a new URL. You indicate the URL through the DataValueField property and the hyperlink text using DataTextField.

The following listing shows a sample application that displays a list of cities and lets users pick one. The page consists of two forms, one with the list of cities and one that shows the result of the choice.

<%@ Page Inherits= "System.Web.UI.MobileControls.MobilePage"
 Language="C#" %>
<%@ Register TagPrefix="mobile"
 Assembly="System.Web.Mobile" %>

 Where do you want to go today?


Figure 11-5 shows the application in action.

click to expand
Figure 11-5: The list of cities as generated by the List control. The presence of the ItemCommand handler makes each item selectable.


Pay attention when you use the $ symbol with mobile applications. In WML, the $ symbol has a special meaning and is used to identify variables. However, ASP.NET mobile controls automatically process occurrences of $ symbols in the source code and render them correctly using a double $$ symbol.

A List control can be bound to a data source by using the DataSource and DataMember properties, whose behavior is identical to what we saw for ASP.NET list-bound controls. It goes without saying that DataSet, DataTable, and DataView objects are good sources for a such a data-bound mobile control.

You should note that the List control can bind only to two columns on the specified data source—one for the Text property of the list item and one for the Value property. These values are set through the DataTextField and DataValueField properties of the List control. By defining a handler for the ItemDataBind, you can also set the text of a list item as the combination of more source fields.

void OnItemDataBind(object sender, ListDataBindEventArgs e) {
 e.ListItem.Text = String.Format ("{0} – ${1}", 
 DataBinder.Eval(e.DataItem, "city"),
 DataBinder.Eval(e.DataItem, "price"));

On devices that support richer rendering, you can specify templates to customize the view of data items. In templated mode, the List control functions similarly to the Repeater ASP.NET server control.

The ObjectList Control

The ObjectList is the mobile counterpart of the ASP.NET DataGrid server control. In particular, the ObjectList can have two views—list and details. In list view, the control displays a sort of menu made of the values of a single field. This has been done to accommodate devices with small screens. The LabelField property lets you choose which bound field is to be used to populate the quick menu. Each displayed item is clickable and generates a detail view in which all the fields in the current data row are displayed. The way in which the item is made clickable is device specific.

The detail view can include a toolbar with all the commands specified using the tag plus the back command, whose text is set through the BackCommandText property. Finally, the AutoGenerateField property (which is true by default) along with the elements let you decide which bound fields are to be actually displayed. As you can easily guess, this feature mimics the column auto-generation feature of ASP.NET DataGrid controls that we examined in Chapter 6, "Creating Bindable Grids of Data."

The ObjectList differs from the List control in some respects. One is that the ObjectList allows you to associate multiple commands with each item. The set of commands for an item can be either shared among all items or unique to the item. Other differences are that the ObjectList supports multiple views and doesn't support static items. Later on in this chapter, when building a sample application, we'll use an ObjectList control to display some data.

The List and ObjectList controls fully support internal pagination. Both controls also provide a feature known as custom pagination, which closely resembles the custom paging of Web DataGrid controls. Normally, paginated controls require that all the data they need be provided at once. Custom paginated controls, on the other hand, fire the LoadItems event when they display a new portion of the user interface. Developers specify the total number of items in the ItemCount property. Changing the value of the ItemCount property from its default value of zero to the total number of items indicates that the control is to be custom paginated. The LoadItems event handler is expected to retrieve the appropriate data and bind it to the control.

The SelectionList Control

In the gallery of mobile list-bound controls, the SelectionList control is unique in that it provides UI selection capability for a list of items. Like a drop-down list or a check-box list, it shows a list of items and can allow users to select one or more items. When an item is selected, no server-side event is automatically generated, as happens in certain Web list controls when the AutoPostBack property is set to true. The SelectedIndexChanged event is generated for the change of selection.

The SelectionList control can be rendered in five different selection types: drop-down (default), radio button, check box, list box, and multiselection list box. You choose the selection type by using the SelectType property. Not all devices support all these selection types. Typically, a cell phone will recognize only check-box and multiselection types, so radio button, list box, and drop-down are rendered with a pick list.

The following listing shows how to display a list of selectable items and how to retrieve all the selected items:

<%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" 
 Language="C#" %>
<%@ Register TagPrefix="mobile"
 Assembly="System.Web.Mobile" %>

 Your skills?

Figure 11-6 shows the application in action.

click to expand
Figure 11-6: A check-box SelectionList control in action on a cell phone.

Text Controls

The TextControl class is an abstract class from which some navigation and input controls derive. All text-based controls have a Text property, which can be programmatically set and is usually used to render the output of the control. Link, TextBox, and Label are examples of controls derived from the TextControl class. The Label mobile control is similar to the ASP.NET Label control and the Link mobile control looks a lot like the ASP.NET HyperLink control. Other text controls are the Command control, which logically represents a command button, and the PhoneCall control.

The TextBox Control

The TextBox control generates a single-line text box and stores in the Text property the text that a user enters. The control can work in password or numeric mode, but it doesn't support multiline editing or the read-only attribute. Alignment and maximum length are other advanced characteristics of the control.


The TextBox control also supports the OnTextChanged server-side event, which executes the specified handler if the text changes between two successive postbacks of the same page.

The Command Control

The Command control sums up most of the characteristics of the ASP.NET Button and LinkButton controls. It can be rendered as a submit button (default) or as a hyperlink. It can also be rendered as an image. The Format property lets you choose between Button and Link; if the output format is Link, you can also choose an image to display as a clickable element. The image is set through the ImageUrl property. If the device supports softkeys, the output of the Command control can just be the label of one of the softkeys. (A softkey is a programmable button available on many cell phones.)

Any click on a Command control causes a postback event. You can set the server-side code in either of two ways—the ItemCommand or OnClick event handler. With the ItemCommand event handler, you must also give the control a command name and, optionally, a command argument. When the control is clicked, the CausesValidation Boolean property determines whether the control has to perform validation on all other controls in the same form.

The following listing shows how to use a TextBox and Command control:

 Search for: 


The ActiveForm property on a Form object programmatically gets or sets the form's currently active form. Figure 11-7 shows the application in action.

click to expand
Figure 11-7: TextBox and Command controls in action.

The PhoneCall Control

The PhoneCall control is an output-only control that is used to represent a phone number to call. For devices that support placing phone calls (for example, cell phones), the control looks like an interactive element that makes a call when clicked. On other nonvoice devices, the phone number is displayed as a link to a URL or, optionally, as plain text.

Phone numbers found for Joe:

The AlternateFormat property can be any string and is used to represent the control on devices without telephony capabilities. It can accept two parameters, one having the value of Text and the other having the value of PhoneNumber. The alternate text is rendered as plain text unless the AlternateURL property is specified. In this case, the control generates a hyperlink that points to the specified URL. If the Text property is unspecified, the phone number is also used for display. Note that a large number of Nokia phones don't support this feature.

Validation Controls

All validation mobile controls inherit from an abstract class named BaseValidator, which in turn descends from the TextControl base class. All controls share a Text and ErrorMessage property. The Text property becomes the output of the control in case of an invalid entry. If the Text property is not set, the validator displays the value of the ErrorMessage property instead. The value stored in ErrorMessage is also the text that gets displayed in the ValidationSummary control. This behavior is identical to what we saw in Chapter 3, "ASP.NET Core Server Controls," for Web Forms validators. Mobile controls include five validators.

  • CompareValidator This control compares the values of two controls by using the specified comparison operator. The ControlToValidate property indicates the ID of the control to validate. The value against which the validation should occur can be indicated either explicitly—the property ValueToCompare—or indirectly through the ControlToCompare property. This latter property contains the ID of the control to compare against the current ID. While setting up the validator, you can also indicate the type of the data being compared (for example, date, string, or integer) and the required operator (for example, greater-than or not-equal-to).
  • CustomValidator This control allows you to validate the value of a control by using your own method. You use the ControlToValidate property to indicate the control being verified and write your own validation code handling the server-side ServerValidate event. To inform the run time about the outcomes of the process, you set the IsValid property of the event data structure to true or false, as appropriate.
  • RangeValidator This control ensures that the values of another control fall within the specified range. The MinimumValue and MaximumValue properties set the bounds of the range. You can also indicate the type of the values being compared. You do this through the Type property. The range must include both bounds. If you need to check values without an upper or lower bound, use the CompareValidator instead.
  • RegularExpressionValidator This control verifies that the value of a given control matches the specified regular expression. ControlToValidate indicates the control to keep under observation and ValidationExpression sets the pattern to match.
  • RequiredFieldValidator This control makes an input control a required field. You should note, though, that a required field isn't necessarily an empty field. The concept of requirement applies to any value that is different from the contents of InitialValue. The validation is successful only if the value of the control is different from the initial value upon losing focus.

When validators are used within a page, ASP.NET can display a summary of the validation errors, if any. This task is accomplished by the ValidationSummary control. The control collects all the error messages set for the various validators, organizes them in an all-encompassing string, and displays the resulting text in a secondary form. The BackLabel property lets you set the text for the Back button that restores the failed form.

The Command control is the only mobile control that causes validation of input data in the form. TextBox and SelectionList are, on the other hand, the only mobile controls whose value can be validated. In particular, Text is the validation property of the TextBox control and SelectedIndex is the validation property of the SelectionList control. However, other controls (for example, custom and user controls) can participate in the validation process with their own properties. To do so, they need to be marked by the ValidationPropertyAttribute attribute.

The following listing shows how to set up a page that validates the user input. The page contains a SelectionList control that enumerates possible skills to communicate to the company. At least one skill must be specified, though. We use a RequiredFieldValidator control associated with the SelectionList. In this case, the InitialValue is automatically set to -1.

ErrorMessage="Must indicate a skill!"
ControlToValidate="skills" />

 Indicate your skills


 Recognized skills

When the user clicks to submit data, the page interrogates all the contained validators to see whether they have valid data. If the IsValid property of the MobilePage is set to false, the procedure aborts and the same form is rendered back to the client with the validator that now displays its error message. If one is needed, you can use a ValidationSummary control in a secondary form that can be activated on demand. Figure 11-8 shows the previous code in action.

click to expand
Figure 11-8: Validating the user input through mobile validation controls.

Developing Mobile Applications

To wrap up what we've learned so far about mobile controls and mobile pages, let's build an application that is representative of a typical wireless scenario. Depending on the capabilities of the device, you normally build a mobile application to cache information that will later be transmitted to a back-end system, or to interact in real time with the back-end system. The former scenario is more common for rich and smart devices such as the Pocket PC family of products. For their modest processing power and RAM, cell phones are typically used for interacting with systems. However, the limited hardware and software capabilities of such devices makes it challenging for developers to build effective and usable wireless applications. A typical scenario for mobile applications is the search of information. I've chosen to focus on this category of programs because of the repercussions it has on a critical aspect of wireless applications—usability.

Our goal in this section is building a mobile application that lets users retrieve information about a customer and perhaps place a call. Of course, the subject of the search—customers—is totally arbitrary. The pattern applies with any large database to be navigated through. The term large is used here in a relative sense—that is, the databases in question are large in the context of the display capabilities of mobile devices. If displaying 20 records at a time makes sense for conventional Web applications, you should never exceed a few units (and compact ones at that) of data for an application that is used through a small-screen cell phone. Another key point to consider is the input capabilities of the device. Again, while letting the user type a matching string to narrow the set of customers being retrieved is sensible in the Web world, in a wireless context such an action has to be reckoned with the (normally very limited) input capabilities of the device and subsequently with the high level of frustration the poor user might soon reach.

The CustomerFinder Application

Our goal is to build a customer finder application—that is, an application that lets you retrieve personal information about a particular customer you would like to call or visit if only you could remember her darn phone number. The rub, though, is that you can't afford to keep hundreds of addresses and phone numbers in your cell phone. If you're using a smarter device, well, then imagine that you simply forgot to synchronize it with the database before you left the office!

Devising the Application for Usability

Many Web and desktop applications let you perform searches in an incremental way. You enter a string that is a partial key and the system soon prompts you with all the keys that match. Next, you further narrow the list by using a less partial key or simply picking the right one from the displayed list. This way of working makes perfect sense as long as you have enough screen space and memory. But there's an extra, often unnoticed, asset you normally have if you're working at your desk—the keyboard. In general, with mobile devices you can easily enter numbers but not free text. So using a text box to type the key and a button to access the server is a rather unfair approach—easy for you as a developer, but annoying for the poor user who could be trying to use that application with only one hand while walking or eating.

A general guideline for wireless applications can be summarized in the following slogan: one more click is a more enjoyable torture than having to type text. In a wireless application, especially if you know it will be used through cell phones, data entry should be avoided altogether or, at least, limited only to when it's absolutely necessary. You should use any information you might have about the user (for example, name, e-mail address, profile, and even global position) to personalize the screen and present options in a way that is optimized for the specific user.

The structure of a form must be as terse as possible, with short but effective descriptions and just one way of accomplishing tasks. Data should be downloaded in small chunks for bandwidth reasons and using the application should be as easy as scrolling and clicking softkeys or numbers in the keypad.

A good design pattern for mobile applications that require input from the user is that of wizards. A tree-based representation of the tasks and the data to obtain is the key, as it makes it easier for you to submit a list of options to simply click or leave.

With this in mind, let's move on and build a serious mobile application using Visual Studio .NET and its pretty cool Mobile Designer.

The Mobile Designer in Visual Studio .NET

To build a true mobile application in Visual Studio .NET 2003, you should pick up an ASP.NET Mobile Web Application from the New Project dialog box, as shown in Figure 11-9.

click to expand
Figure 11-9: The first step in building an ASP.NET Mobile Web Application is choosing the right project type in Visual Studio .NET.

Beyond that, nothing is really different from building a conventional ASP.NET Web application. An ad hoc designer module—the ASP.NET Mobile Designer—appears to help you create mobile forms and fill them with controls and code. Controls cannot be resized because resizing is handled by ASP.NET when it generates the actual markup code for a particular device. You should try to organize the user interface of the application in forms, and provide commands to move from one form to the next.

The Mobile Designer offers an abstract representation of pages, meaning it does not emulate the rendering of any specific device. The page might appear quite differently at run time from how it appears at design time. Consider that the target device might not support every control property or the value you assigned. The BackColor property, for example, is supplied and can be set, but it's used only on smart devices, such as the Pocket PC. As we'll see later, developers can customize pieces of the application to control how it looks on a particular device.

Figure 11-10 shows the structure of the user interface we're going to build.

Figure 11-10: The outline of the CustomerFinder application. It consists of three forms. The first two let you navigate to the desired customer, whereas the third one displays information.

The CustomerFinder application consists of three forms. The first two forms (main form and second menu form) have a similar structure. Both display a list of options from which you can choose the customer to call. The first main form employs a List control to display a static list of options, each of which selects customers whose company name begins with any letter in a range (for example, A through F). In addition, a text box lets you enter a partial key to locate all the customers that match it.

The second menu form shows the results of the previous search. If you selected a range of letters, the second menu form displays all of them so that you can narrow the working set further by indicating the particular letter. This is probably a better option than presenting a long list of about 20 letters. (I say 20 because with a slightly smarter SQL query, you could, for example, skip letters for which there's no registered customer.) The second menu form also contains a text box and a command button to let you narrow further the list of customers. However, at this stage the content of the text box is validated and forced to be any string that starts with any of the displayed letters. For example, if you're viewing letters between A and F, you're not allowed to enter a partial key like GA. The validation is implemented using a CustomValidator control.

Finally, the third customer form displays the list of selected customers using an ObjectList control. Using and configuring all these controls is in no way different from using equivalent controls for an ASP.NET Web application. Figure 11-11 shows the main form of the application.

Figure 11-11: The main form of the CustomerFinder application as it appears in the Openwave emulator.

Working with Emulators

By default, Visual Studio .NET uses an internal browser to test and debug mobile applications. However, you can also install your own device emulator and use it to browse the application.

Once the emulator has been downloaded and installed on the machine, you can register it with Visual Studio .NET through the Browse With item under the File menu. When you select Browse With, the Browse With dialog box shown in Figure 11-12 appears. You locate the emulator executable, give it a friendly name, and you're done. Note that once the emulator has been added to the list, its settings cannot be edited further. You have to remove it and add it again with proper settings.

click to expand
Figure 11-12: The dialog box used to install a browser emulator within Visual Studio .NET.

By selecting an emulator and clicking the Browse button in the Browse With dialog box, you can browse the current application using a particular device without leaving the development environment. If you set an emulator as the default browser, Visual Studio .NET will launch it whenever you debug an application.

Openwave (which you can learn more about at provides a handful of emulators, each with different characteristics for the WML language and a range of supported devices. Another suite you might want to try is YourWap. You can get it from Of course, Mobile Internet Explorer and the Pocket PC emulator are other embedded tools you can use to quickly get an idea about the areas, if any, in which your mobile user interface is lame.

Suffice it to say that although ASP.NET mobile Web applications do a fantastic job of abstracting the various wireless markup languages and fusing them to the .NET Framework, a lot remains to be done. In particular, you should be aware that ASP.NET alone is not enough to build real-world mobile applications that work great on a wide range of devices. This is not because of flaws and shortcomings in the ASP.NET implementation, however. It's more the result of the deep differences, in both hardware and software, existing between devices. For this reason, you should carefully consider the possibility of extending the ASP.NET mobile code with device-specific extensions. We'll discuss device-specific extensions later in the "Adaptive Rendering" section.

The Navigation Model of the Application

As mentioned earlier, the CustomerFinder application is composed of three server- side forms. The first two forms let you narrow the set of customers to be displayed. When a reasonably small number of customers has been reached, the data is passed on to an ObjectList component for display.

If you look at this strategy from a pure Web perspective, you might find it questionable, to say the least. However, designed this way, a mobile application is easier to use because it requires the user only to push buttons to proceed. The overall set of data is seen as a tree and is traversed by making a logical choice at each step. Only small chunks of information need to be downloaded at any stage. Because the Customers table is likely to be used by all sessions, it needs to be downloaded only once and stored in the ASP.NET Cache object for better performance. The data is loaded when the application starts.

void Application_Start(object sender, EventArgs e) {
 DataSet data = LoadDataFromDatabase();
 Context.Cache["Customers"] = data;

The Main Form

The first form to display employs a List control to display four options that, when combined, cover the 26 letters of the alphabet. The Text property of the ListItem object indicates the range, while the Value property contains all letters included separated by a comma.


The main form is completed with a text box and a command button. If the button is clicked, the text in the input field is used to select and display, in the customer form, a subset of customers. If you click on one of the list items, the following code executes:

void Menu_ItemCommand(object sender, ListCommandEventArgs e) {
 string[] menuItems = e.ListItem.Value.Split(",".ToCharArray());
 Session["AvailableInitials"] = menuItems;
 LetterList.DataSource = menuItems;

 // Move to the second form
 ActiveForm = SecondMenuForm;

The comma-separated list of letters is split into a string array and temporarily parked in the session cache. We might need to retrieve it later to validate any text the user should enter in the Find text box for a more direct search. The same array of strings is used to fill another List object. In this case, the instance of the List control is bound to dynamically generated data rather than to static data.

The ActiveForm property gets and sets the currently active form in a mobile page class. When a page is initially rendered, the first form in the page is automatically activated and displayed. On subsequent postbacks, another form might be brought to the foreground, either programmatically or as the result of user navigation. The ActiveForm property is a fundamental element for the implementation of wizard- like mobile user interfaces. In this case, the ActiveForm property is set to the second menu form.

The Second Menu Form

The second menu form (shown in Figure 11-13) shows all the letters that were listed in the Value property of the selected ListItem object.

Figure 11-13: The second menu form with a restricted menu as it is displayed by the Openwave emulator.

You should note at this point how device output can differ even when the same markup is submitted. The Openwave browser uses a numbered list of options that can be selected by pushing numbers on the phone keypad. The Nokia browser, on the other hand, allows only position-based selection.

The code for the second menu form is shown here:


When the user clicks any of the individual letters displayed, the code prepares a sort of in-memory query and gets back with an ADO.NET DataView object with all customers whose name begins with the selected letters. The customers are listed using an ObjectList control.

If the user wants to type a string to restrict the search, there's a text box available at the bottom of the second menu form. The text you can type is subject to validation; only strings that start with any of the listed letters are acceptable. The following listing shows the code for the custom validator:

void ServerValidate(object source, ServerValidateEventArgs e) {
 e.IsValid = false;

 // Ensure that the contained value begins with any of the listed letters
 string[] menuItems = (string[]) Session["AvailableInitials"]; 
 string currentValue = e.Value.ToLower();
 foreach (string s in menuItems)
 if (currentValue.StartsWith(s.ToLower())) {
 e.IsValid = true;

The effect of validation is shown in Figure 11-14. Note that, for usability reasons, you should place the validator at the very top of the form so that its error message is the first thing the user sees once the page posts back.

click to expand
Figure 11-14: The user entered unexpected text, and the validator caught it.

The Customer Form

As the final step in our CustomerFinder application, let's display customers. We'll use an ObjectList control and bind it to the collection of rows selected by the following code:

DataView SelectCustomers(string filterString) {
 string cmdText = ""; 
 string[] initials = filterString.Split(",".ToCharArray());
 string opOR = "";

 // Build the filter string for ADO.NET view filters
 foreach(string s in initials) {
 cmdText += String.Format("{0} {2} LIKE '{1}%' ", 
 opOR, s, "companyname");
 opOR = " OR ";

 // Build the filtered view
 DataTable data = GetData();
 DataView view = new DataView(data);
 view.RowFilter = cmdText;
 return view;

The code sets up a view on top of the global table of customers that was downloaded upon startup. The filtered view is then assigned to the DataSource property of ObjectList control.

void LetterList_ItemCommand(object sender, ListCommandEventArgs e) {
 DataView view = SelectCustomers(e.ListItem.Value); 
 CustomerList.DataSource = view;

 ActiveForm = CustomerForm;

The customer form is shown in Figure 11-15.

Figure 11-15: The customer form showing the list of customers to select from.

The structure of the customer form is shown as follows:


The ObjectList control first displays a list of the values bound through the LabelField column. When you click any of these items, a detail view is provided that includes all the rows for which a element exists. The collection of displayed fields must include the label field—Company, in the preceding example. If you don't want it to be displayed, set the Visible attribute to false. The Name attribute allows you to alias the physical data field. The detail view of the customer is shown in Figure 11-16.

Figure 11-16: The long-awaited information about the customer.

The detail view provided by the ObjectList control, as well as the List control, can be customized to some extent using templates.


In WML, a Web page is typically referred to as a card. A group of cards is called a deck. Most WML-based browsers have a limitation on the size of the deck they can receive. This is known as the deck size limit, and it can vary according to the individual device. Because the limit applies to content compiled at the WAP gateway, it's difficult to determine whether a WML deck is too large for a device. Exceeding the size limit could easily lead to a deck overflow error. This is particularly a risk for dynamic, data-bound pages.

You should note that ASP.NET doesn't truncate pages to make decks fit within the deck size limit of a device. To be on the safe side, programmers should either use pagination within the form or consider approximately 1,200 characters as a realistic threshold for decks.

Adaptive Rendering

Mobile applications can adapt the appearance of controls to specific devices or to categories of devices. Because they are based on known device capabilities, you can vary the style of the controls as well as make the rendering of the control more or less rich to accommodate the device characteristics. Adaptive rendering is performed using device filters. A device filter is represented with a tag in the controls layout.

Understanding Device Filters

The ASP.NET runtime abstracts the .aspx code and generates appropriate markup for rendering on a variety of device types. However, when you need different code to be generated for the same control on a device-by-device basis, you should define a set of device filters for the application and then specify the code to generate for each filter. You express a device filter using the and elements.

The element is merely a container that holds a number of choices. Choices represent pairs made from a device characteristic and the corresponding value. The device filters are defined in the web.config file. A choice is selected if the filter is verified—that is, if the attribute of the device and the value match. The following listing demonstrates some filters that can be defined in web.config:


The element has a name that is used to bind to the element. The compare attribute defines the capability of the device you want to test. The argument property is the value to match. For example, if you want a label to render in italic on HTML 3.2 devices and as normal text elsewhere, do the following:



Note that this technique works as long as you have the filter defined in the web.config file. Choices are evaluated in the order they appear in the construct. In practice, a device filter is a declarative way to test some capabilities of the device and configure the control properly.

Creating Control Templates

Device filters can also be used to change the default template used by list controls. For example, in the example just discussed we end up displaying the phone number of the selected customer. Wouldn't it be nice if we could automatically associate it with a PhoneCall control? In this way, in fact, our user could click and place a call. Both the List and ObjectList controls let you change the structure of the default template. The following code shows how to change the template used to render all the items of a List object using a PhoneCall control:


If the Filter property is omitted, the choice is picked by default, and this allows you to modify the output of some built-in controls using templates.

State Management

Most Web applications need state to be persisted between requests, and mobile applications are no exception. ASP.NET provides several services and facilities for state management, among which view state and session state play a primary role. View state is a page-level cache that is saved and loaded for each request of the page. This trick makes possible the development of stateful applications on top of a stateless protocol.

ASP.NET also provides a session-state object that can be used to save information across multiple requests. As we'll see more in detail in Chapter 14, "ASP.NET State Management," session management in ASP.NET is more scalable and robust than in previous versions of ASP and can also be used across Web farms.

The View State

On ASP.NET Web Forms pages, the view state is packed as a hidden variable in the unique server-side form object that is submitted. The view state is sent back and forth as part of every response and request being exchanged. The way in which applications interact with the view state is the same in ASP.NET mobile applications. The internal implementation is different, however.

To reduce bandwidth, ASP.NET does not send the view state of a mobile page to the client. Instead, the view state remains on the server and is saved as part of the user's session. The view state is cached in a slot named ViewState in which an object of type SessionViewStateHistory is saved. The SessionViewStateHistory type is a super-array of SessionViewStateHistoryItem objects in which the actual view state of the page—generated as in ASP.NET Web Forms—is stored. Because the view state is kept on the server, it's possible for the currently cached state and the currently displayed page to be out of sync. For example, suppose the user navigates to a given page and then moves back to another page by using the Back button. At this point, the current page doesn't match the view state on the server.

For this reason, ASP.NET maintains for mobile pages a history of view states on the server. Each page is assigned a numeric ID that corresponds to the position in the view-state history where information about that page is held. The size of the history array is set to 6 by default, but it can be changed in the web.config file, as shown in the following code. Of course too high a value might lead to unnecessary consumption of server memory.


Because the view state of mobile pages and controls is stored in Session, chances are that this information will get lost if the session expires or the process is recycled. When the view state can't be restored for a mobile page, the ViewStateExpire event is fired. The event normally results in an exception being thrown; however, if there's a way for the application to restore a consistent state on a view-state failure, you should override the method OnViewStateExpire on the MobilePage class and execute your recovery code there.

Just as for ASP.NET Web Forms, the use of the view state can be minimized and completely disabled if it's not really needed. You can disable the view state by using the EnableViewState attribute on the @Page directive; if you want to disable the view state for an individual control, use the EnableViewState property on the control's programming interface.

The Private View State

You should note, though, that even when the view state is disabled, mobile controls might save state information in a hidden field on the client. For example, a MobilePage control saves the index of the currently active form in a hidden field implemented in a way that closely resembles the Web Forms view state. The view-state history identifier is also saved in this sort of private view state.

The ClientViewState property returns a string that represents the serialized version of the private view state. Applications cannot add custom information to this table. The private view state should be used only for general state information, is always saved to the client, and cannot be disabled.


The HiddenVariables collection of the MobilePage class provides a way to create hidden variables in the output. Although this feature has nothing to do with the private view state, it represents an easier-to-use alternative to the private view state.

The Session State

The session state is tied to an identifier that uniquely identifies the session within the application. By default, this identifier is stored in a client-side cookie and is retrieved across round-trips. Using cookies in mobile applications can be problematic because some devices and gateways do not support cookies.

ASP.NET supports cookieless sessions. A cookieless session relies on a special format of the URL to retrieve the identifier. When working in cookieless mode, ASP.NET redirects the browser to another page whose URL embeds the identifier, which is then parsed out of the actual URL. In this case, though, you should pay attention to devices that might experience difficulty if passed a URL with special formatting such as the URL of a cookieless application.

Hidden variables are a fair alternative to using the session state in the unfortunate case in which you can't afford it.

The Extensibility Model

The built-in set of mobile controls can be extended by using the same guidelines as for Web controls. Therefore, you can create user and custom controls. Mobile user controls inherit from the base class MobileUserControl and are stored in files with an .ascx extension. Unlike ASP.NET user controls, mobile user controls can contain child forms. To link to a form in a user control, you must use a combined ID made of the ID of the control and the ID of the embedded form—UserControl:Form. A child form can reference a form in the parent container simply by name. When this happens, ASP.NET recursively searches for a matching form, proceeding from the user control all the way up to the root page.

You can also create custom controls that inherit from existing mobile controls. You can add new properties, methods, and events and override existing elements. Custom controls can be created either to extend the capabilities of a single particular control or as a composite control. With composite controls, you programmatically combine existing controls and expose them as a new monolithic object. This is a slightly different procedure than with user controls. The key difference is that composite controls are deployed as assemblies, are inheritable, and enjoy full support from the Visual Studio .NET designers.

Extensibility in the .NET mobile world is not limited to controls but spans to cover new devices and new device adapters. You can add a new device browser by adding a new entry to either the web.config or machine.config file. This is far easier than writing a new device adapter, which is a relatively complex class. However, in situations in which the particular capabilities of the device cannot be described declaratively, writing a new device adapter is necessary.


Developing mobile applications can be quite a complex task because of differences in browser presentation models and gateways. Like it or not, the market for wireless devices is fragmented, although this fragmentation is possibly stronger in Europe than in other parts of the world. So to be on the safe side and deploy effective applications, you should multi-author your application for each relevant class of devices. Writing multiple applications is not usually an attractive prospect to developers and managers, who are understandably reluctant to give the green light on such projects.

In the wireless world, though, the difference between devices is too large to be effectively addressed in all cases even by a well-written library such as the ASP.NET mobile controls. The need to deal with radically different sets of capabilities forces developers to implement navigation models, data entry capabilities, and strictly device-specific commands. If you're going to build mobile applications for multiple devices, your best chance is to endow yourself with a server-side programming library that abstracts the presentation of content from the underlying platform. ASP.NET mobile controls do just this and much more. There are several key plusses in ASP.NET mobile applications.

For one thing, ASP.NET mobile controls are fully integrated with the .NET platform, meaning that you can leverage the full potential of the .NET Framework with its over 7,000 ready-to-use classes. In addition, the Mobile Designer integrated with Visual Studio .NET 2003 lets you build mobile applications in an intuitive manner and with a very short learning curve if you're already a .NET developer. (Also Web Matrix supports mobile projects.) Finally, mobile development in the .NET world is language agnostic.

Aside from the .NET platform, other server-side libraries have been developed in the community with the declared goal of abstracting both the differences in the vendor's implementations of the WML language and the hardware device capabilities. An example of this approach is the Open Usability Interface (OUI) originally developed by Openwave and then transformed into an open-source project. With a more limited scope than ASP.NET, OUI is optimized for rendering on Nokia and Openwave browsers. OUI is available for download at

In this chapter, we presented an overview of ASP.NET mobile controls, trying to emphasize all relevant aspects but not digging too deep into any of them. Building mobile applications, especially for multiple devices, is a huge topic that deserves an entire book of its own. This chapter concludes the overview of ASP.NET controls. In the next part of the book, we'll look at programming aspects that are essential for setting up real-world ASP.NET applications. We'll return to controls in Part V in time to cover custom controls.


  • Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition, by Andy Wigley and Peter Roxburgh (Microsoft Press, 2003)
  • Mobile ASP.NET Web Applications (

Part IV ASP NET Application Essentials

Programming Microsoft ASP. NET
Programming Microsoft ASP.NET 3.5
ISBN: 0735625271
EAN: 2147483647
Year: 2005
Pages: 209
Authors: Dino Esposito © 2008-2020.
If you may any questions please contact us: