Introduction to Mobile Controls


Mobile controls are the ASP.NET solution to creating Web applications that are usable by multiple platforms. The current release supports HTML 3.2, WML 1.1, and cHTML browsers, and allows third party customization for other types of output (such that the controls could be extended to cover whatever odd Internet access technologies might appear in the future). The motivation behind this is to create a set of controls that will perform equally well on multiple devices and yet be programmable using device independent syntax.

The techniques for using mobile controls are similar to those required for other ASP.NET controls, so much of the code may look familiar to you, particularly that required for event handling etc. However, there are differences in the way pages are structured to contain mobile Web controls, many of which are due to the limitations of mobile devices as discussed earlier. In particular, multiple forms can be contained within a single mobile control Web page, necessary to create a system analogous to multiple WML cards in a single deck.

As is often the case when trying to explain a new programming paradigm, it is easiest to start with an example to show the basic operation of mobile controls in action.

Simple Example

For this example we'll create a mobile controls page similar to the simple example discussed earlier in the chapter. The code, example1.aspx , is as follows :

  <%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="VB" %>   <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"   Assembly="System.Web.Mobile" %>     <mobile:Form Runat="server" id="first" Title="First Page">   Welcome!<br/>   <mobile:Link Runat="server" NavigateURL="#second">   Continue   </mobile:Link>   <mobile:Link Runat="server" NavigateURL="http://www.somewhere.com/">   Home   </mobile:Link>   </mobile:Form>     <mobile:Form runat="server" id="second" Title="Second Page">   Now into content...   </mobile:Form>  

The first two lines of code are required for any mobile Web form application, setting up the base class for the page:

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

And the mobile controls namespace:

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

These two lines of code are often called the prolog of a mobile Web form.

Note that the TagPrefix attribute here specifies mobile as the prefix for mobile controls. Although you can use a different prefix, this is not advised as this may cause compatibility problems with pages made using Visual Studio .NET.

The body of the page consists of two <mobile:Form> controls. Each of these can be thought of as a card for display on a WAP device, or a page for display in an HTML browser. The first of these forms contains some plain text and two <mobile:Link> controls, to display hyperlinks “ complete with NavigateURL attributes pointing to the second form and an external link. The second form just contains some text.

Don't worry too much about the exact functionality of these controls for now; all of this will be covered later in the chapter.

Again, take a brief look at the results, first on the Nokia 5100 simulator shown in Figure 21-11:

click to expand
Figure 21-11:

Points to notice for this device (in comparison with the earlier example and in a general sense):

  • A back link is placed in both cards. The mobile controls automatically place these in every card generated.

  • Both links are generated as hyperlinks.

  • Links appear in the same line of text if there is enough space.

Next look at the Openwave Simulator in Figure 21-12:

click to expand
Figure 21-12: Figure courtesy Openwave Systems Inc.

Although it looks slightly different, the functionality is the same. However, the code produced by the controls is quite different, as you will see in the next section. Figure 21-13 shows this page on the Sony Ericsson T610 Simulator (available from http://www.ericsson.com/mobilityworld/):

click to expand
Figure 21-13:

Finally, as mobile control pages can also generate HTML, you can look at the results in an HTML browser on a PDA. One way of doing this, and the method I'll use, is to use the Pocket PC 2003 Emulator described earlier. You could also use Microsoft Explorer and simply reduce the window size , but this way is more accurate (Figure 21-14):

click to expand
Figure 21-14:

The first page shows the specified text along with a hyperlink to the second page, while the second simply produces the expected string.

The HTML results here do look quite bare, but it is possible to customize HTML output such that it could be considered for a professional Web site “ using templates and style properties.

Viewing Generated Code

In each browser used in the last section, different code was generated. Most browsers enable you to view the sourcecode for the page being displayed (that is, the code generated by the ASP.NET processor, not the ASP.NET code itself). However, this is not always the case.

It can be useful to see the code generated by an ASP.NET page containing mobile controls, to see exactly what is happening and enabling you to further customize your code as required. The easiest way to do this is to impersonate the device from a separate ASP.NET page, which will call pages containing mobile controls sending the required headers ( HTTP_USER_AGENT , HTTP_ACCEPT , and a few others related to device capabilities) to get the tailored response.

Well, to save you the trouble I've created just such a page: impersonate.aspx, which is available in the code download for this chapter. The interface is shown in Figure 21-15:

click to expand
Figure 21-15:

If you select a device (I've included a few more browsers here “ it's simple enough to add more to the code if you know the HTTP headers for a device), enter a URL (try the example from the last section) and press Get Result you will see the resultant code in the text box as shown in Figure 21-16:

click to expand
Figure 21-16:

Using this tool you can see the code generated for the two devices in the last section. This is the result for the Nokia 5100:

  <?xml version='1.0'?>   <!DOCTYPE wml PUBLIC '-//WAPFORUM//DTD WML 1.1//EN'   'http://www.wapforum.org/DTD/wml_1.1.xml'>     <wml>   <head>   <meta http-equiv="Cache-Control" content="max-age=0" />   </head>     <card id="first" title="First Page">   <do type="prev" label="Back">   <prev />   </do>   <p>   Welcome!   <br/>   <a href="#second" title="Link">Continue</a>   <a href="http://www.somewhere.com/" title="Home">Home</a>   </p>   </card>     <card id="second" title="Second Page">   <do type="prev" label="Back">   <prev />   </do>   <p>   Now into content...   </p>   </card>   </wml>  

This is the result for the Openwave Simulator:

  <?xml version='1.0'?> <!DOCTYPE wml PUBLIC '-//WAPFORUM//DTD WML 1.1//EN' 'http://www.wapforum.org/DTD/wml_1.1.xml'>      <wml>    <head>       <meta http-equiv="Cache-Control" content="max-age=0" />    </head>         <card id="first" title="First Page">       <p>          Welcome!          <do type="accept" label="Go">             <go href="/MC/example1.aspx" method="post">                <postfield name="__EVENTTARGET" value="first" />                <postfield name="__EVENTARGUMENT" value="$(first)" />             </go>          </do>          <select name="first">             <option onpick="#second">Continue</option>             <option onpick="http://www.somewhere.com/">Home</option>          </select>       </p>    </card>         <card id="second" title="Second Page">       <do type="accept">          <noop />       </do>       <p>          Now into content...       </p>    </card> </wml>  

As you can see, the two versions are quite different. Don't worry about any WML elements you don't recognize “ in most cases you don't need to know exactly what they mean. However, it is worth looking at those that make up the main differences between these pieces of code.

The <select> and <option> elements are used by WML to build list selection fields. On the Openwave Simulator these are rendered as numbered lists, allowing selection either by hitting a softkey or by pressing the appropriately numbered button on the device “ a quick and intuitive solution to lists of up to 10 choices. Unfortunately, list selection fields aren't rendered like this on other devices. It can be tricky to select an item from these on, for example, the Nokia 5100, and no numeric keypad shortcuts are available. This is why hyperlinks are used instead on the Nokia simulator, and the <a> element is used as shown in the preceding code.

Also the code for the Openwave Simulator contains code that is common to ASP.NET pages “ the postback information. This isn't required for simple links such as the one used for the Nokia 7110 simulator. But, when you use many controls to generate more complex pages it is worth keeping an eye on this added info . Remember that there is quite a small size limit for WML pages “ if the compiled version is larger than around one and a half KB you'll start to run into problems. As a final note on this link rendering, be aware that the code generated can vary in certain circumstances “ see the notes on the <mobile:Link> control in the control reference section of this chapter.

This is the first example we've seen of different WML being generated for different devices “ without any intervention on our part. This is good “ you can relax in the knowledge that ( assuming the mobile controls development team do their job properly and keep up with current devices) the code you write will be effectively tailored for multiple client devices.

Wherever WML code is detailed in this chapter, it has been extracted using this simple tool, which will save you the effort of downloading and installing multiple WAP browsers. Note, however, that some devices are not supported by the version of the mobile controls available at the time of writing. If you generate code using these, you will see the HTML code as generated for IE. It is possible to extend the configuration of the mobile controls yourself to cater for such devices, but this is an advanced topic that I don't want to get into here.

Mobile Control Forms

All mobile controls in ASP.NET pages are held in <mobile:Form> forms. As you saw in the last example, each of these corresponds to a single display. The form currently being displayed is held in the ActiveForm property of the page, which you can set programmatically to change the display “ something you will often do in event handlers for controls.

You can see a quick example of this by making use of one of the events that <mobile:Form> forms generate. They create two events, which (unsurprisingly) occur when a given form is activated or deactivated, and are called OnActivate and OnDeactivate accordingly . You can assign event handlers for these controls using identically named attributes on any given form, and create event handlers in the standard way. So, to view the id for the currently active form you could use the following (not particularly useful, but illustrative ) code:

  <%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="VB" %>   <%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls"   Assembly="System.Web.Mobile" %>     <mobile:Form runat="server" id="first" OnActivate="first_OnActivate">   Now in form:   <mobile:Label runat="server" id="content"/>   </mobile:Form>   <script runat="server" language="VB">   Sub first_OnActivate(sender As Object, e As System.EventArgs)   content.Text = ActiveForm.ID   End Sub   </script>  

Here the Text property for the <mobile:Label> control with the ID attribute of content to the ID property of the currently active form “ in this case first . The result for this is shown in Figure 21-17:


Figure 21-17:

As this is simple text there is no need to show the result in other browsers (throughout this chapter I'll only show multiple browsers where the results are pertinent).

In addition to the runat , id , title , OnActivate , and OnDeactivate attributes for forms there are a few more you should take a brief look at. Several of these enable you to set styles for form content. These are common to all mobile controls, and any that are set for a form will propagate down into contained controls. You can also set up common style references elsewhere using simple stylesheets, and use the StyleReference attribute of a form or contained control to set up multiple style properties simultaneously , using reusable styles. This is covered in the Styling section later in this chapter.

For now, here is a list of the common style attributes, shared by all the mobile controls:

  • StyleReference

  • Font (broken down into sub-properties as per standard server controls)

  • ForeColor

  • BackColor

  • Alignment

  • Wrapping

As well as sharing the preceding attributes, all mobile controls also share the following three:

  • BreakAfter

  • EnableViewState

  • Visible

BreakAfter determines whether a control should have a line break after its own rendering, EnableViewState whether the control should store its own state between postbacks, and Visible whether it should be rendered at all. All of these attributes may be True or False , where the default is True .

Form controls also have some properties concerning pagination. As you can't fit huge amounts of text on a mobile screen, it is often useful to split text over several cards, and perhaps even decks. The pagination properties are as follows:

  • Paginate

  • OnPaginate

We'll look at the use of these later in the chapter, in the section on pagination. However, other pagination-related attributes appearing on other controls will be noted in the following section for later reference.

Finally, there are two properties controlling the postback operation of the form:

  • Action

  • Method

Action is used to specify an alternative URL to use for posting information if required, and Method selects the HTTP method ( Get or Post ) used for postback information.

Control Reference

In this section you will look at each of the controls available in the mobile controls collection (with the exception of <mobile:StyleSheet> , which is examined in the Styling section) along with examples of their usage and details of their properties and available events. We'll start with the simpler visual controls and finish up with the validation controls, which are similar to their standard ASP.NET control counterparts.

Note that all controls contain the standard id and runat attributes (where runat must be server for all controls) as well as the styling attributes listed in the last section, so these won't be listed with the attributes for each control. Also, attributes pertaining to events will be listed in a separate Events section where appropriate.

<mobile:Label>

This is a simple control, allowing you to output simple text to a browser. You can do this using plain text as we've already seen, but this control lets you make programmatic changes to its text via the Text property, in the same way as the <asp:Label> control does for non-mobile ASP.NET pages.

On WAP devices this control will result in text being placed inside a <p> element in the card created by the <mobile:Form> form that contains the <mobile:Label> control. For HTML, output text is inserted as a simple literal.

Attributes

Attribute

Description

Text

The text to output to the browser.

Code Generated

On the WAP simulators this generates the following code in a card:

  <p>   Text<br/>   </p>  

For HTML browsers the following code is generated:

  Text  

This is contained inside the <form> for the page.

Example Usage

As you saw in the earlier example:

  <mobile:Form runat="server" id="frmFirst">   <mobile:Label runat="server">Welcome!</mobile:Label>   </mobile:Form>  

The label text may be set either by the Text attribute or by enclosing text inside the element (although the attribute value always takes precedence). The preceding code could be rewritten, with no change to the results, as:

 <mobile:Form runat="server" id="frmFirst">  <mobile:Label runat="server" Text="Welcome!"/>  </mobile:Form> 

As this example generates simple text, the likes of which you have already seen, we won't show screenshots of the resultant displays here.

<mobile:Link>

This control is another one that you have already seen in action, and generates the UI code required to create a simple hyperlink.

Attributes

Attribute

Description

NavigateUrl

The destination URL for the link. If preceded with a # character this refers to the id of a mobile form within the current page.

SoftkeyLabel

The label to display on a softkey when the link is selected, if supported on the target browser.

Text

The text to output to the browser.

Code Generated

This control can generate three types of code, depending on whether the target of the link is another form in the same page, whether further processing is required for a second page, and whether several links are placed next to each other in a single form. In simple cases, the WML generated for a single link control will be as follows:

  <a href="NavigateURL" title="SoftKeyLabel">Text</a>  

On some WAP devices, a softkey alternative will also be generated, meaning the link can be followed even if it isn't visible on screen owing to scrolling. In this case the code generated will be:

  <do type="accept" label="SoftKeyLabel">   <go href="NavigateURL" />   </do>  

The HTML generated is generally along the lines of:

  <a href="NavigateURL">Text</a>  

OR:

  <a href="javascript:__doPostBack('ctrl5','frmSecond')">Text</a>  

depending on the task required and the various forms that postback operations can take (simply adding a SoftkeyLabel attribute will result in the latter code). There will also be a __doPostBack() function defined on the page, together with the usual hidden data for the viewstate, etc.

As demonstrated in the earlier example, the WML created for multiple links can vary a great deal depending on the device, and may be rendered as several <a> elements or a <select> / <option> list.

Example Usage

The following code generates simple, postback, and <select> / <option> links depending on the browser:

  <mobile:Form runat="server" id="first" Title="First">   <mobile:Link runat="server"   NavigateUrl="http://www.somewhere.com/somefile.aspx">   External Link   </mobile:Link>   <mobile:Link runat="server"   NavigateUrl="http://www.somewhere.com/somefile.aspx"   SoftkeyLabel="Ext">   External Link with label   </mobile:Link>   <mobile:Link runat="server" NavigateUrl="#second">   Internal Link   </mobile:Link>   <mobile:Link runat="server" NavigateUrl="#second" SoftkeyLabel="Int">   Internal Link with label   </mobile:Link>   </mobile:Form>     <mobile:Form runat="server" id="second" Title="Second">   2nd Card   </mobile:Form>  

Try using this along with additional forms, etc. to see the various code generated, using Impersonate.aspx .

<mobile:Image>

This control enables you to embed images in your forms. WAP supports a single image format, known as Wireless Bitmap Images, or WBMPs. This format is (once again) optimized for low bandwidth systems, as it can display only two color (one bit) images. Various editors are available on the Web for creating such images, and various plugins are available for existing image editors.

This control requires you to make a choice of image based on the browser being used. Later in the chapter this is covered more detail, but for now look at the simple case of distinguishing between HTML and WML browsers.

The mobile controls require you to add filters to the web.config file for your application in order to check against device capabilities stored in machine.config . A simple filter for WML1.1 and HTML3.2 devices requires the following code to be added to web.config :

 <?xml version="1.0" encoding="utf-8" ?> <configuration>    <system.web>            ...  <deviceFilters>   <filter name="isHTML32" compare="preferredRenderingType"   argument="html32" />   <filter name="isWML11" compare="preferredRenderingType"   argument="wml11" />   </deviceFilters>  </system.web> </configuration> 

Note that creating mobile Web forms in Visual Studio .NET will result in several device filters being added to your initial web.config file by default, including the preceding code.

You can then refer to these filters by placing a <DeviceSpecific> element inside the <mobile:Image> element, which in turn contains one or more <Choice> elements. These <Choice> elements allow you to make modifications to the <mobile:Image> control, based on specified filters. These modifications take the form of overriding properties of the <mobile:Image> control. The following usage selects one of two images depending on whether the browser is WML 1.1:

  <mobile:Image runat="server" ImageUrl="NonWML1.1URL">   <DeviceSpecific>   <Choice ImageUrl="WML1.1URL" Filter="isWML11"/>   </DeviceSpecific>   </mobile:Image>  

Attributes

Attribute

Description

AlternateText

Text to display if no image can be displayed in the browser being used (rendered as a label control).

ImageUrl

URL of image to display for the command. The default is null .

NavigateUrl

A URL to navigate to if the image is interacted with, if desired (and supported).

SoftkeyLabel

The label to display on a softkey when the image is selected, if supported on the target browser.

Code Generated

The code generated is identical for all browsers, as the WML syntax is identical to the HTML syntax:

  <img src="Filename" alt="AlternateText"/>  

The only difference in the generated code will be the filename specified.

Example Usage

The following code displays a picture I took of a friend's lizard , in one of two formats, depending on the browser used:

  <mobile:Form runat="server" id="first">   <mobile:Image runat="server" AlternateText="Lizard" ImageUrl="lizard.bmp">   <DeviceSpecific>   <Choice ImageUrl="lizard.wbmp" Filter="isWML11"/>   </DeviceSpecific>   </mobile:Image>   </mobile:Form>  

The results are shown in Figure 21-18:

click to expand
Figure 21-18:

<mobile:Command>

This control enables you to place a UI element that the user can interact with in some way, resulting in a call to an event handler (either a simple click event or a custom item event, which will be bubbled up to parent controls). For HTML output this control results in a button; the WML result varies.

Attributes

Attribute

Description

CausesValidation

Whether the control is authenticated; True (the default) or False .

CommandArgument

The argument associated with the command in OnItemCommand .

CommandName

The name that identifies the command in OnItemCommand .

Format

Can be Button or Link . Sets the rendering style for the control.

ImageUrl

URL of image to display for the command. The default is null .

SoftkeyLabel

The label to display on a softkey when the link is selected, if supported on the target browser.

Text

The text to output to the browser.

Events

Event

Description

OnItemCommand

Occurs when the user interacts with the UI element generated and bubbled up to parent controls, if any.

OnClick

Occurs when the user interacts with the UI element generated.

Code Generated

For HTML pages this results in an <input> element if format is set to Button , for example:

  <input name="id" type="submit" value="Text"/>  

or a simple <a> element if format is set to Link .

The WML varies. A softkey may be generated:

  <do type="accept" label="Text">   <go href="command.aspx?631151558034057424" method="post">   <postfield name="__VIEWSTATE"   value="YjU2NTJiNTktODVlNS00YTVhLThjZWMtYWJjYmRkZmIzOTQ3LDA=f0da65f6" />   <postfield name="__EVENTTARGET" value="id" />   <postfield name="id" value="$(id)" />   </go>   </do>  

Alternatively, and particularly on the Openwave Simulator, a <select> list may be generated with an <option> element allowing the command to be called, in much the same way as for <mobile:Link> .

Note that the ImageUrl property, which determines an image to display on a device if that device supports graphics, works in the same way as the equivalent property of the <mobile:Image> control, with device-specific rendering supported in the same way.

Example Usage

The following code contains some text that changes when the Press button is pressed:

  <mobile:Form runat="server" id="first" Title="First">   <mobile:Label runat="server" id="result">   Button not pressed.   </mobile:Label>   <mobile:Command runat="server" id="button1" Text="Press"   SoftkeyLabel="Press" OnClick="button1_OnClick"/>   </mobile:Form>   <script runat="server" Language="VB">   Sub button1_OnClick(sender As Object, e As System.EventArgs)   result.Text = "Button pressed!"   End Sub   </script>  

Figure 21-19 shows how the button appears on various devices:

click to expand
Figure 21-19:

<mobile:TextBox>

This control enables user input. The output in all cases will be a text box, although the functionality of the WML rendition of this varies significantly between browsers.

It is possible to change the type of textbox displayed using the Numeric and Password attributes. If both of these are false you get a plain text box, setting Numeric to true gives a number only textbox, and setting Password to True renders a password mode text box, where asterisks are written to the screen to prevent unwanted reading of passwords.

However, I personally think that the Password type only causes confusion on mobile devices, as it makes the already awkward text input even harder (it's easy to lose your place) and “ to be honest “ who's likely to read your password over your shoulder on a tiny LCD screen?

Attributes

Attribute

Description

MaxLength

The maximum number of characters allowed in the text box.

Numeric

True or False . Indicates whether the text box is numeric.

Password

True or False . Indicates whether the text box acts in password mode.

Size

The size of the control in characters.

Text

The text to output to the browser.

Events

Event

Description

OnTextChanged

Occurs when the user modifies the text in the text box (and a post back is triggered)

Code Generated

For HTML and WML browsers (again, the syntax is identical):

  <input name="id" [type="password"]/>  
Example Usage

The following code uses text input for a simple login page:

  <mobile:Form runat="server" id="first">   Enter name:   <mobile:TextBox runat="server" id="name"/>   Enter password:   <mobile:TextBox runat="server" id="password" Password="true"/>   <mobile:Link runat="server" NavigateUrl="#second" Text="Login"   SoftkeyLabel="Login"/>   </mobile:Form>   <mobile:Form runat="server" id="second" OnActivate="second_OnActivate">   <mobile:Label runat="server" id="result"/>   </mobile:Form>   <script runat="server" Language="VB">   Sub second_OnActivate(sender As Object, e As System.EventArgs)   if ((name.Text = "Karli") AND (password.Text = "Cheese")) then   result.Text = "Welcome Karli!"   Else   result.Text = "Sorry, " & name.Text & ", your password is not " _   & "recognized."   End If   End Sub   </script>  

The first form takes a name and password; the second displays the login result. This result is calculated by frmSecond_OnActivate() , which is called when the name and password are submitted (or, more accurately, when frmSecond is activated). The simple algorithm used simply checks if the name is Karli and the password is Cheese , else it displays a failure message.

It is worth noting another fairly major difference between browsers here. Although the code generated for different WAP devices is very similar, the user experience can vary a great deal. Most browsers display the input boxes in a form-like interface, for example the Nokia 5100 shown in Figure 21-20:


Figure 21-20:

Here, selecting a field in the Nokia simulator takes you to a separate data entry screen, and when you return the fields are updated.

However, the Openwave Simulator interface allows direct input to the fields displayed. Once the pencil softkey is selected, you can use the rest of the keys on the phone to type text directly on screen, much like in a Pocket PC form (Figure 21-21):

click to expand
Figure 21-21: Figure courtesy Openwave Systems Inc.

When text is entered and the softkey is selected, the display moves on to the password entry field, and finally to the Login link. The end effect is the same, but the routes there can vary.

<mobile:List>

This control allows for simple non-interactive lists of items in plain text, a list of commands, or a list of links. Whatever you want to do with this control you can specify the items it contains using <Item> elements within the control, or programmatically (using the exposed Items collection). A very simple list, used for display only, might therefore look like this:

  <mobile:List runat="server">   <Item Text="Richard Anderson"/>   <Item Text="Brian Francis"/>   <Item Text="Alex Homer"/>   <Item Text="Dave Sussman"/>   <Item Text="Karli Watson"/>   </mobile:List>  

Each of the <Item> elements may also have a Value property, which specifies a destination when link lists are used. To obtain a link list, simply set the ItemsAsLinks property to true :

  <mobile:List runat="server" ItemsAsLinks="true">   <Item Text="Richard Anderson" Value="http://www.richardanderson.com/"/>   <Item Text="Brian Francis" Value="http://www.brianfrancis.com/"/>   <Item Text="Alex Homer" Value="http://www.alexhomer.com/"/>   <Item Text="Dave Sussman" Value="http://www.davesussman.com/"/>   <Item Text="Karli Watson" Value="http://www.karliwatson.com/"/>   </mobile:List>  

Alternatively, you can specify an event handler to execute when an item is selected using OnItemCommand , although this won't work properly if ItemsAsLinks is true . The control also supports standard ASP.NET data binding.

Attributes

Attribute

Description

DataMember

When databinding, this attribute specifies the table of a DataSet to use.

DataSource

When databinding, this attribute specifies the data source to use.

DataTextField

When databinding, this attribute specifies the field to use for item text values.

DataValueField

When databinding, this attribute specifies the field to use for item- value values.

Decoration

None , Bulleted , or Numbered “ allows for extra formatting of item text by adding bullet marks or numbering items.

ItemCount

The amount of items to display when using pagination, where a value of 0 means to choose this value automatically.

ItemsAsLinks

True or False . Whether to render items as links.

ItemsPerPage

The number of items to display per page when using pagination, where a value of 0 means to use the default value.

Events

Event

Description

OnItemCommand

Occurs when an individual list item generates a command event. Note that this won't work if ItemsAsLinks is true.

OnItemDataBind

Occurs when an item is databound.

OnLoadItems

Occurs when pagination is being used and the items to display are requested .

Code Generated

Obviously, this control can generate varied code. For simple lists the output will be plain text, with appropriate line breaks, or formatted as a table. Link lists will generate code appropriate to the device, such as <select> fields or anchors. For example, the preceding code generates the following HTML on a Pocket PC:

  <table>   <tr>   <td>   <a href="http://www.richardanderson.com/">Richard Anderson</a>   </td>   </tr>   <tr>   <td>   <a href="http://www.brianfrancis.com/">Brian Francis</a>   </td>   </tr>   <tr>   <td>   <a href="http://www.alexhomer.com/">Alex Homer</a>   </td>   </tr>   <tr>   <td>   <a href="http://www.davesussman.com/">Dave Sussman</a>   </td>   </tr>   <tr>   <td>   <a href="http://www.karliwatson.com/">Karli Watson</a>   </td>   </tr>   </table>  

The WML generated on a Nokia 5100 is as follows:

  <a href="http://www.richardanderson.com/">Richard Anderson</a>   <a href="http://www.brianfrancis.com/">Brian Francis</a>   <a href="http://www.alexhomer.com/">Alex Homer</a>   <a href="http://www.davesussman.com/">Dave Sussman</a>   <a href="http://www.karliwatson.com/">Karli Watson</a>  

And the WML generated on Openwave browsers is along the lines of:

  <do type="accept" label="Go">   <go href="example.aspx?__ufps=631274647595414160" method="post">   <postfield name="__VIEWSTATE"   value="aDxfX1A7QDw7MmI1YjhiMTgtYWROGExOTg1LDA7Pjs+" />   <postfield name="__EVENTTARGET" value="ctrl0" />   <postfield name="__EVENTARGUMENT" value="$(ctrl0)" />   </go>   </do>   <select name="ctrl0">   <option onpick="http://www.richardanderson.com/">Richard Anderson</option>   <option onpick="http://www.brianfrancis.com/">Brian Francis</option>   <option onpick="http://www.alexhomer.com/">Alex Homer</option>   <option onpick="http://www.davesussman.com/">Dave Sussman</option>   <option onpick="http://www.karliwatson.com/">Karli Watson</option>   </select>  

Each of these pieces of code is entirely appropriate for the target device.If you are generating a list of commands then appropriate post back code will also be generated.

Example Usage

As a quick example of a command list, consider the following modified code:

  <mobile:Form runat="server" id="first">   <mobile:List runat="server" id="List1"   OnItemCommand="List1_OnItemCommand">   <Item Text="Richard Anderson"   Value="http://www.richardanderson.com/"/>   <Item Text="Brian Francis"   Value="http://www.brianfrancis.com/"/>   <Item Text="Alex Homer"   Value="http://www.alexhomer.com/"/>   <Item Text="Dave Sussman"   Value="http://www.davesussman.com/"/>   <Item Text="Karli Watson"   Value="http://www.karliwatson.com/"/>   </mobile:List>   </mobile:Form>     <mobile:Form runat="server" id="second">   Follow this link for <mobile:Label runat="server" id="name"/> homepage:   <mobile:Link runat="server" id="homepage" Text="Link"   SoftkeyLabel="Link"/>   </mobile:Form>     <script runat="server" Language="VB">     Sub List1_OnItemCommand(sender As Object, _   e As System.Web.UI.MobileControls.ListCommandEventArgs)   name.Text = e.ListItem.Text & "'s"   homepage.NavigateURL = e.ListItem.Value   ActiveForm = second   End Sub     </script>  

When the user selects an item from the list they are redirected to the second card by the command event handler, which also provides a link to the homepage specified in the item value attributes.

Note that the ActiveForm property is set to the id of the target form without enclosing the id in double quotes.

<mobile:SelectionList>

This control is similar to <mobile:List> , but has a few important differences. First, it doesn't support pagination. Second, multiple item selection is permitted, aided by the fact that selecting individual items doesn't necessarily trigger a postback. Third, it maintains a list of what items are selected. Finally, the UI is different.

There are two methods of accessing selected items. For single selection lists you can look at the Selection and SelectedIndex properties of the control. However, for multiple selection lists you must examine the Selected property of each item in the Items collection of the control.

Attributes

Attribute

Description

DataMember

When databinding, this attribute specifies the table of a DataSet to use.

DataSource

When databinding, this attribute specifies the data source to use.

DataTextField

When databinding, this attribute specifies the field to use for item text values.

DataValueField

When databinding, this attribute specifies the field to use for item value values.

Rows

For HTML and cHTML devices, this attribute gets or sets the number of rows displayed in the selection list.

SelectType

DropDown (the default), ListBox , Radio , MultiSelectListBox , or CheckBox . Determines the rendering style.

Title

Text used for selection list title in some WML devices.

Events

Event

Description

OnItemDataBind

Occurs when an item is data bound.

OnSelectedIndexChanged

Occurs when a post back is performed and the selected items have changed.

Code Generated

The code generated for this control varies a great deal from HTML output, to cater for the various input methods, although for WML it is always a <select> / <option> list. As a postback isn't generated by default you also need to add a method of doing this manually, such as a button or link.

Example Usage

The following code generates a multiple selection check box list and displays the items selected when a <mobile:Command> control is manipulated:

  <mobile:Form runat="server" id="first">   <mobile:SelectionList runat="Server" id="List1" runat="server"   SelectType="CheckBox" Title="Authors">   <Item Text="Richard Anderson" />   <Item Text="Brian Francis" />   <Item Text="Alex Homer" />   <Item Text="Dave Sussman" />   <Item Text="Karli Watson" />   </mobile:SelectionList>   <mobile:Command id="nextForm" runat="server" SoftkeyLabel="Next"   Text="Next" onClick="nextForm_click"/>   </mobile:Form>     <mobile:Form runat="server" id="second">   Selected:   <mobile:Label id="names" runat="server"/>   </mobile:Form>     <script runat="server" Language="VB">     Sub nextForm_click(sender As Object, e As System.EventArgs)   Dim selectionCount As New Integer()   Dim item As MobileListItem   selectionCount = 0   names.Text = ""   For Each item In List1.Items   If item.Selected Then   If selectionCount <> 0 Then   names.Text += ", "   End If   names.Text += item.Text   selectionCount += 1   End If   Next   If selectionCount = 0 Then   names.Text = "None"   End If   ActiveForm = second   End Sub     </script>  

Remember that you can only use the Selection and SelectedIndex properties of List1 to get information on single selection lists, hence the For...Each loop is used in the previous code to interrogate all items in the list.

On the Pocket PC this is rendered as shown in Figure 21-22:

click to expand
Figure 21-22:

The rendering on the Sony Ericsson T610 Simulator is shown in Figure 21-23:

click to expand
Figure 21-23:

The Nokia 5100 interface is slightly trickier to use and involves more steps, but it still works. One advantage, though, is that the Title attribute ( Author ) is recognized and displayed, as shown in Figure 21-24:

click to expand
Figure 21-24:

<mobile:ObjectList>

This control enables more complex lists to be defined, where each item is the visual representation (this may vary significantly between browsers)of an object.. This object enables a lot more flexibility “ even in its default usage it allows the user to view additional object information. You can also define multiple fields to view and commands to execute for items, leading to interesting possibilities, as you will see in the next example. Due to this additional functionality, and the difference in rendering when compared to simple lists, no selection attributes exist and items can only be defined by data binding. However, you still have access to the Selection and SelectedIndex properties of a list, which becomes important once a command is executed for an item, as it allows us to tell which item generated the command.

Attributes

Attribute

Description

AutoGenerateFields

True or False “ If True (the default value), then object properties are automatically converted into extra fields for each ObjectListItem object that the list contains.

BackCommandText

Text used for Back link.

DataMember

When data binding to a DataSet , this attribute specifies the table to use.

DataSource

This attribute specifies the data source to use.

DefaultCommand

The default command to execute for an item.

DetailsCommandText

Text used for Details link.

ItemCount

The amount of items to display when using pagination, where a value of 0 means to choose this value automatically.

ItemsPerPage

The number of items to display per page when using pagination, where a value of 0 means use the default value.

LabelField

The field to use for primary display purposes.

MoreText

Text used for More link.

TableFields

The fields to display in table view, as a series of identifiers separated by semicolons.

Events

Event

Description

OnItemCommand

Occurs when an individual list item generates a command event.

OnItemDataBind

Occurs when an item is databound.

OnItemSelect

Occurs when an item is selected.

OnLoadItems

Occurs when pagination is being used and user requests more data.

OnShowItemCommands

Occurs when the defined commands for an item are rendered.

Example Usage

To illustrate this object, let's expand the author list from the last section such that information about each author is stored in an object. First of all, you need to define an author class:

  <script runat="server" Language="VB">     Public Class author   Private authorName, authorInitials, authorFavoritefood As String     Public Sub New(ByVal name As String, ByVal initials As String, _   ByVal favoritefood As String)   authorName = name   authorInitials = initials   authorFavoritefood = favoritefood   End Sub     Public ReadOnly Property name() As String   Get   Return authorName   End Get   End Property     Public ReadOnly Property initials() As String   Get   Return authorInitials   End Get   End Property     Public ReadOnly Property favoritefood() As String   Get   Return authorFavoritefood   End Get   End Property   End Class  

You can then populate the list control, itemList, with an array of author objects. The easiest place to do this is in the Page_Load() event handler (although you only need to do this once, so you can check to see if there is a postback going on):

  Public Sub Page_Load(o As Object, e As EventArgs)   If (IsPostBack = False) Then   Dim authors As New ArrayList   authors.Add(new author("Richard Anderson", "RJA", "Pizza"))   authors.Add(new author("Brian Francis", "BF", "Pasta"))   authors.Add(new author("Alex Homer", "AH", "Steak "))   authors.Add(new author("Dave Sussman", "DS", "Whisky"))   authors.Add(new author("Karli Watson", "KCW", "Fondue"))   lstItems.DataSource = authors   lstItems.DataBind()   End If   End Sub     </script>  

The code for the form itself is very simple. The only thing you need to add is a LabelField attribute, which specifies which field to use for the primary list display:

  <mobile:Form runat="server" id="frmFirst">   <mobile:ObjectList runat="server" id="lstItems" LabelField="name"/>   </mobile:Form>  

The result of all this is more complex than you might expect. Figure 21-25 shows the output on the Pocket PC:

click to expand
Figure 21-25:

Clicking on an author name now has the default effect for this control (we haven't implemented our own handler), which is to show additional information on the author using automatically created fields. Notice that the field names are exactly the same as the class property names. This is because AutoGenerateFields is set to True “ the default. If you change this to False , you can specify how fields are rendered or even if they are rendered at all. This is done by adding <Field> elements inside the control. Each of these elements specifies a field to add to the ObjectListItems in the control. You specify these by what property they should represent (using the DataField attribute), the display name for the field (using the Title attribute), and an id for accessing the field. You can also use the Visible attribute to control whether a given field appears when you follow the automatically generated author name links:

 <mobile:Form runat="server" id="first">  <mobile:ObjectList runat="server" id="lstItems"   AutoGenerateFields="False" LabelField="fName">   <Field Name="fName" Title="Author Name"   DataField="name" Visible="True"/>   <Field Name="fInitials" Title="Author Initials"   DataField="initials" Visible="True"/>   <Field Name="fFood" Title="Author's Favorite Food"   DataField="favoritefood" Visible="False"/>   </mobile:ObjectList>  </mobile:Form> 

These changes result in the output shown in Figure 21-26:

click to expand
Figure 21-26:

As well as adding fields you can also define commands for the items, using <Command> elements. Let's add two commands, to query for a biography or a favorite food:

 <mobile:Form runat="server" id="frmFirst">    <mobile:ObjectList runat="server" id="lstItems"                       AutoGenerateFields="False" LabelField="name">       <Field id="fName" Title="Author Name" DataField="name"              Visible="True"/>       <Field id="fInitials" Title="Author Initials" DataField="initials"              Visible="True"/>       <Field id="fFood" Title="Author's Favorite Food"              DataField="favoritefood" Visible="False"/>  <Command Name="Bio" Text="Author biography"/>   <Command Name="Food" Text="Find out the author's favorite food!"/>  </mobile:ObjectList> </mobile:Form> 

These commands appear as shown in Figure 21-27:


Figure 21-27:

In order to hook up the commands (there are two now) use the OnItemCommand event. First specify a handler by modifying the opening tag for the control:

  <mobile:ObjectList runat="server" id="lstItems"   AutoGenerateFields="False" LabelField="fName"   OnItemCommand="lstItems_itemCommand">  

Next you implement the handler. Here, simply use the item data to specify information for two new forms, shown beneath the code that goes in the <script> section of the page:

  Public Sub lstItems_itemCommand(sender As Object, _   e As ObjectListCommandEventArgs)   Dim currentAuthor As author   If (e.CommandName = "Food") Then   foodLabel.Text = lstItems.Selection.Item("fName") & _   "'s favorite food is " & _   lstItems.Selection.Item("fFood") & "!"   ActiveForm = second   Else   bioLabel.Text = lstItems.Selection.Item("fName") & " biography..."   ActiveForm = third   End If   End Sub   <mobile:Form runat="server" id="second">   <mobile:Label runat="server" id="foodLabel"/>   </mobile:Form>     <mobile:Form runat="server" id="third">   <mobile:Label runat="server" id="bioLabel"/>   </mobile:Form>  

Clicking on an author name then yields the first screenshot in Figure 21-28, and on a 'favorite food' link the second:

click to expand
Figure 21-28:

This is all very well, but how does it appear on a WAP device? Well, on the Nokia 5100 Simulator you see the following card first (Figure 21-29):


Figure 21-29:

When you select an author you get to see the available commands (Figure 21-30):


Figure 21-30:

and these links take you to the relevant command generated forms as shown in Figure 21-31:

click to expand
Figure 21-31:

This is a very powerful control, as you can do far more with the commands than just display information. You could trigger whole chains of business logic in this manner. Again, I'll leave it to you to play with that!

<mobile:PhoneCall>

This control allows the user to call a phone number. Obviously, this isn't appropriate for all devices, so provision is made for those without this capability.

Attributes

Attribute

Description

AlternateFormat

Text to output to devices incapable of making a phone call. This text should include the two placeholders {0} and {1} , which will be replaced with Text and PhoneNumber respectively. The default is " {0} {1} ".

AlternateUrl

Target URL for non-calling devices. If specified, the text in

AlternateFormat

will be rendered as a hyperlink pointing at this URL.

PhoneNumber

Phone number to dial.

Text

Descriptive text to output to the browser.

Code Generated

If the device cannot dial a number then the AlternateFormat text will be output. If the AlternateURL attribute is specified, then the text will be rendered as a hyperlink pointing at the specified URL.

Devices that can dial numbers fall into two categories: some devices, including those using the Openwave Browser, such as the Openwave Simulator, make use of Wireless Telephony Application Interface (WTAI) type commands, in which case the following WML code will do the job:

  <a href="wtai://wp/mc;PhoneNumber" title="Text">Text</a>  

Other devices enable the user to use a number that appears in text, in which case the number will simply be rendered to the screen:

  <p>Text PhoneNumber</p>  

Example Usage

You could use this control in code such as:

  <mobile:Form runat="server" id="first">   <mobile:PhoneCall runat="server" Text="Call Karli's mum"   PhoneNumber="555-1234" AlternateFormat="{0} on: {1}"/>   </mobile:Form>  

The Pocket PC simply renders text as shown in Figure 21-32, as it cannot dial phone numbers (it renders links if you specify AlternateURL ):

click to expand
Figure 21-32:

The Openwave Simulator renders a link that will dial the number, as shown in Figure 21-33:

click to expand
Figure 21-33: Image courtesy Openwave Systems Inc.

And the Nokia 5100 renders the phone number such that it can be selected with the Use Number menu option shown in Figure 21-34:


Figure 21-34:

<mobile:Calendar>

This control is basically the same as the web control with the same name, but is capable of enabling date selection from WAP devices. The UI required to do this is quite different from the HTML version, due to the impossibility of fitting a similar calendar onto a WAP device screen and keeping functionality intact.

The WML version of this control allows you to select dates in two different ways. You can either type one in manually, following the suggested format of MM/DD/YYYY, or choose one by selecting a month, a week, and a day (although not a year for some reason.)

All of the attributes associated with the standard ASP.NET Calendar control are also available, although not declaratively . You can gain access to these using the WebCalendar property of this control, which returns a Web forms calendar control that you can manipulate.

Attributes

Attribute

Description

CalendarEntryText

Text for link into date selection where multiple steps are required (such as in WML browsers).

FirstDayOfWeek

The first day of the week (such as Sunday ). The default value (default) uses the locale settings to determine this attribute.

SelectedDate

The currently selected date, which defaults to TodaysDate .

SelectionMode

day , dayweek , dayweekmonth , none “ what selections are possible from the calendar. The default is day .

ShowDayHeader

true or false . Whether to show day names or just date numbers.

VisibleDate

The month to display “ set by choosing any date in a given month.

Events

Event

Description

OnSelectionChanged

Occurs when a selection is made.

Code Generated

Once again, the code generated by this control is complex, and voluminous. Knowing exactly what this code is doesn't really tell you anything useful, and it would waste a lot of space!

Example Usage

As an example, let's create a page that asks the user what their birthday is. To start off with, I'll initialize the calendar to my birthday (once you know what it is you can all send me presents ), and then prompt for a selection. When the OnSelectionChanged event is raised the user will be asked to confirm the date, which will either complete the procedure or take the user back to the calendar selection. The code is as follows:

  <script runat="server">     Public Sub Page_Load(o As Object, e As EventArgs)   If (IsPostBack = False) Then   birthdayCal.SelectedDate = New DateTime(2004, 9, 17)   birthdayCal.VisibleDate = birthdayCal.SelectedDate   End If   End Sub     Public Sub birthdayCal_selectionChanged(sender As Object, _   e As System.EventArgs)   confirmLabel.Text = "Your birthday is " & _   birthdayCal.SelectedDate.Month.ToString() & "/" & _   birthdayCal.SelectedDate.Day.ToString() & "?"   ActiveForm = confirm   End Sub     </script>     <mobile:Form runat="server" id="calendar">   When is your birthday?   <mobile:Calendar runat="server" id="birthdayCal"   OnSelectionChanged="birthdayCal_selectionChanged"/>   </mobile:Form>     <mobile:Form runat="server" id="confirm">   <mobile:Label runat="server" id="confirmLabel"/>   <mobile:Link runat="server" NavigateURL="#done" Text="Yes"/>   <mobile:Link runat="server" NavigateURL="#calendar" Text="No"/>   </mobile:Form>     <mobile:Form runat="server" id="done">   Done.   </mobile:Form>  

Using the Pocket PC you see the calendar display shown in Figure 21-35:

click to expand
Figure 21-35:

From here you can select a date easily by following any of the day links.

The starting screen in the Nokia 5100 Simulator is shown in Figure 21-36:


Figure 21-36:

When you follow this link you get three more options as shown in Figure 21-37:


Figure 21-37:

The first link, which shows the currently selected date, allows you to confirm a date choice. The other two allow the user to enter a date, either by manually typing it in as shown in Figure 21-38 (with an error message appearing if you enter an invalid date):


Figure 21-38:

or via a series of selection screens as shown in Figure 21-39:

click to expand
Figure 21-39:

Whichever method is used, the same confirmation message appears, where you can choose to keep or discard the selected date.

This control also supports advanced styling using style objects if you extract the Web form control from WebCalendar .

<mobile:TextView>

This control is designed for displaying large volumes of text set at runtime. The only time this control is useful is when you have text containing formatting elements such as <i> and <b> , which aren't allowed in Label controls.

<mobile:AdRotator>

This control is practically identical to the ASP control of the same name, including the way it gets data from an XML file. The only difference is that it can render WML “ it just outputs the AlternateText text for the advert chosen . Since this is the case I will not reiterate its functionality here.

<mobile:Panel>

This control can be used as a container for other controls, including other panels. The main reason for using panels is that they can be useful for grouping controls together. When you do this and use pagination then panel contents will be displayed on single pages if at all possible.

Validation Controls

The Mobile Web SDK contains the following validation controls:

  • <mobile:RequiredFieldValidator>

  • <mobile:RangeValidator>

  • <mobile:CompareValidator>

  • <mobile:RegularExpressionValidator>

  • <mobile:CustomValidator>

  • <mobile:ValidationSummary>

If these look familiar, it's probably because they are once again very similar to their non-mobile counterparts. As such, we're not going to go into a huge amount of detail about these controls, save providing an example of their use and the results they provide.

Example Usage

Let's use a couple of controls in a login form:

  <mobile:Form runat="server" id="first">   Enter name:   <mobile:TextBox runat="server" id="name"/>   Enter password:   <mobile:TextBox runat="server" id="password" Password="true"/>   Confirm password:   <mobile:TextBox runat="server" id="confirm" Password="true"/>   <mobile:Command runat="server" id="enter" Onclick="enter_click"   Text="Enter"/>   <mobile:RequiredFieldValidator runat="server" ControlToValidate="name"   ErrorMessage="Please enter a name" />   <mobile:RequiredFieldValidator runat="server"   ControlToValidate="password"   ErrorMessage="Please enter a password" />   <mobile:RequiredFieldValidator runat="server" ControlToValidate="confirm"   ErrorMessage="Please confirm your password" />   <mobile:CompareValidator runat="server" ControlToValidate="confirm"   ControlToCompare="password"   ErrorMessage="Confirmation must match password" />   </mobile:Form>     <mobile:Form runat="server" id="second">   <mobile:ValidationSummary runat="server" formToValidate="first"   HeaderText="Invalid input"/>   </mobile:Form>   <mobile:Form runat="server" id="third">   <mobile:Label runat="server">Input accepted.</mobile:Label>   </mobile:Form>     <script runat="server">     Public Sub enter_click(sender As Object, e As System.EventArgs)   If (Page.IsValid) Then   ActiveForm = third   Else   ActiveForm = second   End If   End Sub     </script>  

We prompt for a name, a password, and a password confirmation, then check to see if the input is valid. If it is, then a confirmation message is displayed, otherwise the <mobile:ValidationSummary> control is used to output the reasons why the input is invalid. This code also uses the Page.IsValid property to see whether a validation summary is required.




Professional ASP. NET 1.1
Professional ASP.NET MVC 1.0 (Wrox Programmer to Programmer)
ISBN: 0470384611
EAN: 2147483647
Year: 2006
Pages: 243

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net