Article

Constructing ASP.NET Web Pages

Page: 1 2 3 4 5 6 7 Next

ImageMap

The ImageMap control generates HTML to display images that have certain clickable regions called hot spots. Each hot spot reacts in a specific way when it’s clicked by the user.

These areas can be defined using three controls, which generate hot spots of different shapes: CircleHotSpot, RectangleHotSpot, and PolygonHotSpot. Here’s an example that defines an image map with two circular hot spots:

<asp:ImageMap ID="myImageMap" runat="server" ImageUrl="image.jpg">   <asp:CircleHotSpot AlternateText="Button1"    
     Radius="20" X="50" Y="50" />    
  <asp:CircleHotSpot AlternateText="Button2"    
     Radius="20" X="100" Y="50" />    
</asp:ImageMap>


Table 2. Possible values of HotSpotMode

HotSpotMode value Behavior when hot spot is clicked
Inactive none
Navigate The user is navigated to the specified URL.
NotSet When this value is set for a HotSpot, the behavior is inherited from the parent ImageMap; if the parent ImageMap doesn’t specify a defaultvalue, Navigate is set.
When it’s set for an ImageMap, this value is effectively equivalent to Navigate.
PostBack The hot spot raises the Clickevent that can be handled on the server side to respond to the user action.

To configure the action that results when a hot spot is clicked by the user, we set the HotSpotMode property of the ImageMap control, or the HotSpotMode property of the individual hot spot objects, or both, using the values shown in Table 2. If the HotSpotMode property is set for the ImageMap control as well as for an individual hot spot, the latter property will override that set for the more general ImageMap control.

The Microsoft .NET Framework SDK Documentation for the ImageMap class and HotSpotMode enumeration contains detailed examples of the usage of these values.

PlaceHolder

The PlaceHolder control lets us add elements at a particular place on a page at any time, dynamically, through our code. Here’s what it looks like:

<asp:PlaceHolder id="myPlaceHolder" runat="server" />

The following code dynamically adds a new HtmlButton control within the placeholder:

Visual Basic
Public Sub Page_Load()    
 Dim myButton As HtmlButton = New HtmlButton()    
 myButton.InnerText = "My New Button"    
 myPlaceHolder.Controls.Add(myButton)    
End Sub

C#
public void Page_Load()    
{    
 HtmlButton myButton = new HtmlButton();    
 myButton.InnerText = "My New Button";    
 myPlaceHolder.Controls.Add(myButton);    
}

Panel

The Panel control functions similarly to the div element in HTML, in that it allows the set of items that resides within the tag to be manipulated as a group. For instance, the Panel could be made visible or hidden by a Button’s Click event:

<asp:Panel id="myPanel" runat="server">    
 <p>Username: <asp:TextBox id="usernameTextBox" Columns="30"    
     runat="server" /></p>    
<p>Password: <asp:TextBox id="passwordTextBox"    
     TextMode="Password" Columns="30" runat="server" /></p>    
</asp:Panel>    
<asp:Button id="hideButton" Text="Hide Panel" OnClick="HidePanel"    
   runat="server" />

The code above places two TextBox controls within a Panel control. The Button control is outside of the panel. The HidePanel subroutine would then control the Panel’s visibility by setting its Visible property to False:

Visual Basic
Public Sub HidePanel(s As Object, e As EventArgs)    
 myPanel.Visible = False    
End Sub


C#
public void HidePanel(Object s, EventArgs e)    
{    
 myPanel.Visible = false;    
}

In this case, when the user clicks the button, the Click event is raised and the HidePanel subroutine is called, which sets the Visible property of the Panel control to False.

List Controls

Here, we’ll meet the ASP.NET controls that display simple lists of elements: ListBox, DropDownList, CheckBoxList, RadioButtonList, and BulletedList.

DropDownList

A DropDownList control is similar to the HTML select element. The DropDownList control allows you to select one item from a list using a drop-down menu. Here’s an example of the control’s code:

<asp:DropDownList id="ddlFavColor" runat="server">    
 <asp:ListItem Text="Red" value="red" />    
 <asp:ListItem Text="Blue" value="blue" />    
 <asp:ListItem Text="Green" value="green" />    
</asp:DropDownList>

The most useful event that this control provides is SelectedIndexChanged. This event is also exposed by other list controls, such as the CheckBoxList and RadioButtonList controls, allowing for easy programmatic interaction with the control you’re using. These controls can also be bound to a database and used to extract dynamic content into a drop-down menu.

ListBox

A ListBox control equates to the HTML select element with either the multiple or size attribute set (size would need to be set to a value of 2 or more). If you set the SelectionMode attribute to Multiple, the user will be able to select more than one item from the list, as in this example:

<asp:ListBox id="listTechnologies" runat="server"    
   SelectionMode="Multiple">    
 <asp:ListItem Text="ASP.NET" Value="aspnet" />    
 <asp:ListItem Text="JSP" Value="jsp" />    
 <asp:ListItem Text="PHP" Value="php" />    
 <asp:ListItem Text="CGI" Value="cgi" />    
 <asp:ListItem Text="ColdFusion" Value="cf" />    
</asp:ListBox>

RadioButtonList

Like the RadioButton control, the RadioButtonList control represents radio buttons. However, the RadioButtonList control represents a list of radio buttons and uses more compact syntax. Here’s an example:

<asp:RadioButtonList id="favoriteColor" runat="server">    
 <asp:ListItem Text="Red" Value="red" />    
 <asp:ListItem Text="Blue" Value="blue" />    
 <asp:ListItem Text="Green" Value="green" />    
</asp:RadioButtonList>

CheckBoxList

As you may have guessed, the CheckBoxList control represents a group of check boxes; it’s equivalent to using several CheckBox controls in a row:

<asp:CheckBoxList id="favoriteFood" runat="server">    
 <asp:ListItem Text="Pizza" Value="pizza" />    
 <asp:ListItem Text="Tacos" Value="tacos" />    
 <asp:ListItem Text="Pasta" Value="pasta" />    
</asp:CheckBoxList>

BulletedList

The BulletedList control displays bulleted or numbered lists, using <ul> (unordered list) or <ol> (ordered list) tags. Unlike the other list controls, the BulletedList doesn’t allow the selection of items, so the SelectedIndexChanged event isn’t supported.

The first property you’ll want to set is DisplayMode, which can be Text(the default), or HyperLink, which will render the list items as links. When DisplayMode is set to HyperLink, you can use the Click event to respond to a user’s click on one of the items.

The other important property is BulletStyle, which determines the style of the bullets. The accepted values are:

  • Numbered (1, 2, 3, …)
  • LowerAlpha (a, b, c, …)
  • UpperAlpha (A, B, C, …)
  • LowerRoman (i, ii, iii, …)
  • UpperRoman (I, II, III, …)
  • Circle
  • Disc
  • Square
  • CustomImage

If the style is set to CustomImage, you’ll also need to set the BulletStyleImageUrl to specify the image to be used for the bullets. If the style is one of the numbered lists, you can also set the FirstBulletNumber property to specify the first number or letter that’s to be generated.

Advanced Controls

These controls are advanced in terms of their usage, the HTML code they generate, and the background work they do for you. Some of these controls aren’t available to older versions of ASP.NET.

Calendar

The Calendar is a great example of the reusable nature of ASP.NET controls. The Calendar control generates markup that displays an intuitive calendar in which the user can click to select, or move between, days, weeks, months, and so on.

The Calendar control requires very little customization. In Visual Web Developer, select Website > Add New Item…, and make the changes indicated:

Visual Basic LearningASP\VB\Calendar_01.aspx
<%@ Page Language="VB" %>    
   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
   
<script runat="server">    
   
</script>    
   
<html xmlns="http://www.w3.org/1999/xhtml">    
 <head runat="server">    
   <title>Calendar Test/title>    
 </head>    
 <body>    
   <form id="form1" runat="server">    
   <div>    
     <asp:Calendar ID="myCalendar" runat="server" />    
   </div>    
   </form>    
 </body>    
</html>    

Again, the C# version is the same, except for the Page declaration:

C# LearningASP\CS\01_Calendar.aspx (excerpt)

<%@ Page Language="C#" %>

If you save this page in your working folder and load it, you’ll see the output shown in Figure 4.

Displaying the default calendar

The Calendar control contains a wide range of properties, methods, and events, including those listed in Table 3.

Table 3. Some of the Calendar control’s properties

PropertyDescription
DayNameFormat This property sets the format of the day names. Its possible values are FirstLetter, FirstTwoLetters, Full, and Short. The default is Short, which displays the three-letter abbreviation.
FirstDayOfWeek This property sets the day that begins each week in the calendar. By default, the value of this property is determined by your server’s region settings, but you can set this to Sundayor Monday if you want to control it.
NextPrevFormat Set to CustomText by default, this property can be set to ShortMonth or FullMonth to control the format of the next and previous month links.
SelectedDate This property contains a DateTime value that specifies the highlighted day. You’ll use this property often, to determine which date the user has selected.
SelectionMode This property determines whether days, weeks, or months can be selected; its possible values are Day, DayWeek, DayWeekMonth, and None, and the default is Day. When Dayis selected, a user can only select a day; when DayWeek is selected, a user can select a day or an entire week; and so on.
SelectMonthText This property controls the text of the link that’s displayed to allow users to select an entire month from the calendar.
SelectWeekText This property controls the text of the link that’s displayed to allow users to select an entire week from the calendar.
ShowDayHeader If True, this property displays the names of the days of the week. The default is True.
ShowGridLines If True, this property renders the calendar with grid lines. The default is True.
ShowNextPrevMonth If True, this property displays next month and previous month links. The default is True.
ShowTitle If True, this property displays the calendar’s title. The default is False
TitleFormat This property determines how the month name appears in the title bar. Possible values are Monthand MonthYear. The default is MonthYear.
TodaysDate This DateTime value sets the calendar’s current date. By default, this value is not highlighted within the Calendar control.
VisibleDate This DateTime value controls which month is displayed.

Let’s take a look at an example that uses some of these properties, events, and methods to create a Calendar control which allows users to select days, weeks, and months. Modify the calendar in Calendar.aspx (both the VB and C# versions), and add a label to it, as follows:

LearningASP\VB\Calendar_02.aspx (excerpt)
…    
   <form id="form1" runat="server">    
   <div>    
     <h1>Pick your dates:</h1>    
     <asp:Calendar ID="myCalendar" runat="server"    
         DayNameFormat="Short" FirstDayOfWeek="Sunday"    
         NextPrevFormat="FullMonth" SelectionMode="DayWeekMonth"    
         SelectWeekText="Select Week"    
         SelectMonthText="Select Month" TitleFormat="Month"    
         OnSelectionChanged="SelectionChanged" />    
     <h1>You selected these dates:</h1>    
     <asp:Label ID="myLabel" runat="server" />
   
   </div>    
   </form>    


Now edit the <script runat="server"> tag to include the SelectionChanged event handler referenced by your calendar:

Visual Basic LearningASP\VB\Calendar_02.aspx (excerpt)
<script runat="server">    
 Sub SelectionChanged(ByVal s As Object, ByVal e As EventArgs)    
   myLabel.Text = ""    
   For Each d As DateTime In myCalendar.SelectedDates    
     myLabel.Text &= d.ToString("D") & "<br />"    
   Next    
 End Sub
   
</script>

C# LearningASP\CS\Calendar_02.aspx (excerpt)
<script runat="server">    
 void SelectionChanged(Object s, EventArgs e)    
 {    
   myLabel.Text = "";    
   foreach (DateTime d in myCalendar.SelectedDates)    
   {    
     myLabel.Text += d.ToString("D") + "<br />";    
   }    
 }
   
</script>

Save your work and test it in a browser. Try selecting a day, week, or month. The selection will be highlighted in a similar way to the display shown in Figure 5.

Using the Calendar control

In SelectionChanged, we loop through each of the dates that the user has selected, and append each to the Label we added to the page.

AdRotator

The AdRotator control allows you to display a list of banner advertisements at random within your web application. However, it’s more than a mere substitute for creating a randomization script from scratch. Since the AdRotator control gets its content from an XML file, the administration and updating of banner advertisement files and their properties is a snap. Also, the XML file allows you to control the banner’s image, link, link target, and frequency of appearance in relation to other banner ads.

The benefits of using this control don’t stop there, though. Most of the AdRotator control’s properties reside within an XML file; if you wanted to, you could share that XML file on the Web, allowing value added resellers (VARS), or possibly your companies’ partners, to use your banner advertisements on their web sites.

NOTE: What Is XML?
In essence, XML is simply a text-based format for the transfer or storage of data; it contains no details about how that data should be presented. XML is very easy to start with because of its close resemblance to your old friend HTML: both are largely comprised of tags inside angle brackets (< and >), and any tag may contain attributes that are specific to that tag. The biggest difference between XML and HTML is that, rather than providing a fixed set of tags as HTML does, XML allows us to create our own tags to describe the data we wish to represent.

Take a look at the following HTML element:

<h1>Star Wars Episode I: The Phantom Menace</h1>

This example describes the content between the tags as a level one heading. This is fine if all we want to do is display the heading “Star Wars Episode I: The Phantom Menace” on a web page. But what if we want to access those words as data?

Like HTML, XML’s purpose is to describe the content of a document. But where HTML is a very generic markup language for documents—headings, paragraphs and lists, for example—XML can, very specifically, describe what the content is. Using XML, the web author can mark up the contents of a document, describing that content in terms of its relevance as data.

We can use XML to mark up the words “Star Wars Episode I: The Phantom Menace” in a way that better reflects this content’s significance as data:

<film>    
 <title>Star Wars Episode I: The Phantom Menace</title>    
</film>

Here, the XML tag names we’ve chosen best describe the contents of the element. We also define our own attribute names as necessary. For instance, in the example above, you may decide that you want to differentiate between the VHS version and the DVD version of the film, or record the name of the movie’s director. This can be achieved by adding attributes and elements, as shown below:

<film format="DVD">    
 <title>Star Wars Episode I: The Phantom Menace</title>    
 <director>George Lucas</director>    
</film>

If you want to test this control out, create a file called ads.xml in your LearningASP\VB or /#c#/LearningASP\CS folder (or both), and insert the content presented below. Feel free to create your own banners, or to use those provided in the code archive for this book:

LearningASP\VB\Ads.xml
<?xml version="1.0" encoding="utf-8" ?>    
<Advertisements>    
 <Ad>    
   <ImageUrl>workatdorknozzle.gif</ImageUrl>    
   <NavigateUrl>http://www.example.com</NavigateUrl>    
   <TargetUrl>_blank</TargetUrl>    
   <AlternateText>Work at Dorknozzle!</AlternateText>    
   <Keyword>HR Sites</Keyword>    
   <Impressions>2</Impressions>    
 </Ad>    
 <Ad>    
   <ImageUrl>getthenewsletter.gif</ImageUrl>    
   <NavigateUrl>http://www.example.com</NavigateUrl>    
   <TargetUrl>_blank</TargetUrl>    
   <AlternateText>Get the Nozzle Newsletter!</AlternateText>    
   <Keyword>Marketing Sites</Keyword>    
   <Impressions>1</Impressions>    
 </Ad>    
</Advertisements>

As you can see, the Advertisements element is the root node, and in accordance with the XML specification, it appears only once. For each individual advertisement, we simply add an Ad child element. For instance, the above advertisement file contains details for two banner advertisements.

As you’ve probably noticed by now, the .xml file enables you to specify properties for each banner advertisement by inserting appropriate elements inside each of the Ad elements. These elements include:

ImageURL
the URL of the image to display for the banner ad
NavigateURL
the web page to which your users will navigate when they click the banner ad
AlternateText
the alternative text to display for browsers that don’t support images
Keyword
the keyword to use to categorize your banner ad
(If you use the KeywordFilter property of the AdRotator control, you can specify the categories of banner ads to display.)
Impressions
the relative frequency with which a particular banner ad should be shown in relation to other banner advertisements
(The higher this number, the more frequently that specific banner will display in the browser. The number provided for this element can be as low as one, but cannot exceed 2,048,000,000; if it does, the page throws an exception.)

Except for ImageURL, all these elements are optional. Also, if you specify an Ad without a NavigateURL, the banner ad will display without a hyperlink.

To make use of this Ads.xml file, create a new ASP.NET page called AdRotator.aspx, and add the following code to it:

Visual Basic LearningASP\VB\AdRotator.aspx
<%@ Page Language="VB" %>    
   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
   
<script runat="server">    
   
</script>    
   
<html xmlns="http://www.w3.org/1999/xhtml">    
 <head runat="server">    
   <title>Using the AdRotator Control</title>    
</head>    
<body>    
   <form id="form1" runat="server">    
   <div>    
     <asp:AdRotator ID="adRotator" runat="server"    
       AdvertisementFile="Ads.xml" />
   
   </div>    
   </form>    
 </body>    
</html>

As with most of our examples, the C# version of this code is the same except for the Page declaration. You’ll also need to copy the workatdorknozzle.gif and getthenewsletter.gif image files from the code archive and place them in your working folder in order to see these ad images. Save your work and test it in the browser; the display should look something like Figure 6.

Displaying ads using AdRotator.aspx

Refresh the page a few times, and you’ll notice that the first banner appears more often than the second. This occurs because the Impression value for the first Ad is double the value set for the second banner, so it will appear twice as often.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links