ASP 101 - Active Server Pages 101 - Web06
The Place ASP Developers Go!



Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates
ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash



 Top ASP 101 Stories Top ASP 101 Stories
An Overview of ASP.NET
Connections, Commands, And Procedures
What is ASP?

QUICK TIP:
Bracket Your [Table Names] for Access via OLE DB
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates


Converting Our "Tell A Friend" Sample to an ASP.NET User Control

by John Peterson

User controls are one of the things that make developing in ASP.NET more productive then developing in classic ASP. By encapsulating a given set of functionality into a control, it can easily be reused throughout your project with a very minimal amount of effort.

In this article I outline the basic steps that are required to convert an ASP.NET Web Form to an ASP.NET User Control. I then apply them to our Tell a Friend ASP.NET sample code and wouldn't you know it... I end up with a Tell a Friend ASP.NET User Control.

Note: For those of you unfamiliar with ASP.NET user controls, you might want to read our ASP.NET User Controls Lesson before continuing. It should give you enough of an introduction to user controls in order for you to completely understand the code presented in this article.

Why This Sample

We've got quite a few pieces of ASP.NET sample code lying around. So why did I decide to use this one to illustrate how easy it is to convert a piece of code to a user control? Mainly because it seems like a piece of functionality that you might want to put on a number of pages on your site. That's really the only reason. You could do the exact same thing with almost any piece of ASP.NET code, but it just seemed to make sense with this one. Oh and by the way, here's a link to the sample: Tell a Friend ASP.NET Sample.

Step 1: Rename Your Script to .ascx

In order to prevent them from being directly executed, user controls are given the .ascx extension. So, the first step in converting an ASP.NET page (aka. Web Form) to a user control is to change the file's extension from .aspx to .ascx.

Step 2: Remove "Page-Related" Code and HTML

Most ASP.NET pages include HTML elements which help define them as an HTML page. These include <html>, <head>, <body>, <title>, etc. Since this control will now be hosted within another HTML page, these are no longer needed or desirable within the control itself.

In addition to HTML, most ASP.NET pages also include a page directive which looks something like this:

<%@ Page Language="VB" %>

as their first line. Once again... this needs to be removed since the script in question will no longer be a page in an of itself. As a control, it will live within the scope of the page that hosts it.

Step 3: Remove the Server-Side Form Tag

Most ASP.NET pages include a server-side form tag. Since any given ASP.NET page can only contain one of these tags you'll probably need to remove it from your control. If your control requires one, you'll need to ensure that the hosting page provides it.

Step 4: Create Your Hosting Page

You may not be starting from scratch here, but here's a list of the bare minimum that the page that hosts your control should contain:

  • A line to register your control. Here's the line from the code that accompanies this article:

    <%@ Register TagPrefix="asp101" TagName="TellAFriend" Src="tell_a_friend.ascx" %>

  • A server-side form tag as I mentioned above.

  • At least one instance of your new control:

    <asp101:TellAFriend id="ctrlTAF" runat="server" />

Our Code

Aside from wrangling the form and HTML elements down to a managable size and a few changes to the way the script figures out what URL to send in the message, I haven't done anything to the original script aside from the steps outlined above. So instead of me rambling on, take a look for yourselves:

tell_a_friend.ascx
<%@ Import Namespace="System.Web.Mail" %>
<script language="VB" runat="server">
  Sub Page_Load(Source As Object, E As EventArgs)
    If Not Page.IsPostBack Then
      Dim strBody As String
      strBody = "I found a web page I thought you'd like to see:" _
	    & vbCrLf & vbCrLf _
        & "http://" & Request.ServerVariables("HTTP_HOST") _
        & Request.ServerVariables("URL") & vbCrLf
      txtMessage.Text = strBody
    End If
  End Sub
  Sub btnSendMsg_OnClick(Source As Object, E As EventArgs)
    Dim myMessage    As New MailMessage
    Dim myAttachment As MailAttachment
    Dim myMail       As SmtpMail
    If Page.IsValid() Then
      myMessage.From    = txtFromEmail.Text
      myMessage.To      = txtToEmail.Text
      myMessage.Subject = "Check out ASP 101!"
      myMessage.Body    = txtMessage.Text & vbCrLf _
        & "This message was sent from: " _
        & Request.ServerVariables("SERVER_NAME") & "." _
        & vbCrLf & vbCrLf _
        & "This email was sent to " & txtToEmail.Text & "."
      ' Doesn't have to be local... just enter your
      ' SMTP server's name or ip address!
      myMail.SmtpServer = "localhost"
      myMail.Send(myMessage)
      lblMessageSent.Text = "Your message has been sent to " _
	    & txtToEmail.Text & "."
    End If
  End Sub
</script>
<table border="1" cellspacing="0" cellpadding="0">
<tr><td>
<p align="center"><strong>Tell a Friend:</strong></p>
<table border="0" cellspacing="1" cellpadding="1">
  <tr>
    <td valign="top" align="right">Your Name:</td>
    <td>
      <asp:RequiredFieldValidator runat="server"
        id="validNameRequired" ControlToValidate="txtFromName"
        errormessage="Please enter your name:<br />"
        display="Dynamic" />
      <asp:TextBox id="txtFromName" size="20" runat="server" />
    </td>
  </tr>
  <tr>
    <td valign="top" align="right">Your Email:</td>
    <td>
      <asp:RequiredFieldValidator runat="server"
        id="validFromEmailRequired" ControlToValidate="txtFromEmail"
        errormessage="Please enter an email address:<br />"
        display="Dynamic" />
      <asp:RegularExpressionValidator runat="server"
        id="validFromEmailRegExp" ControlToValidate="txtFromEmail"
        ValidationExpression="^[\w-]+@[\w-]+\.(com|net|org|edu|mil)$"
        errormessage="Please enter a valid email address:<br />"
        Display="Dynamic" />
      <asp:TextBox id="txtFromEmail" size="20" runat="server" />
    </td>
  </tr>
  <tr>
    <td valign="top" align="right">Friend's Email:</td>
    <td>
      <asp:RequiredFieldValidator runat="server"
        id="validToEmailRequired" ControlToValidate="txtToEmail"
        errormessage="Please enter an email address:<br />"
        display="Dynamic" />
      <asp:RegularExpressionValidator runat="server"
        id="validToEmailRegExp" ControlToValidate="txtToEmail"
        ValidationExpression="^[\w-]+@[\w-]+\.(com|net|org|edu|mil)$"
        errormessage="Please enter a valid email address:<br />"
        Display="Dynamic" />
      <asp:TextBox id="txtToEmail" size="20" runat="server" />
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <asp:TextBox id="txtMessage" Cols="30" TextMode="MultiLine"
        Rows="5" ReadOnly="True" runat="server" />
    </td>
  </tr>
  <tr>
    <td> </td>
    <td><asp:Button id="btnSend" Text="Send Message"
      OnClick="btnSendMsg_OnClick" runat="server" /></td>
  </tr>
</table>
<asp:Label id="lblMessageSent" runat="server" />
</td></tr>
</table>

This is just a sample page to host the control that I whipped up for illustration. There's not much to it aside from what is needed for the control itself.

tell_a_friend.aspx
<%@ Page Language="VB" %>
<%@ Register TagPrefix="asp101" TagName="TellAFriend"
  Src="tell_a_friend.ascx" %>
<html>
<head>
<title>ASP.NET User Control Hosting Page</title>
</head>
<body>
<form runat="server">
<h2>ASP 101's Tell A Friend ASP.NET User Control Hosting Page</h2>
<p>
This is some other content on the page that is unaffected
by the operation of the control.
...
</p>
<table align="right">
  <tr><td>
    <asp101:TellAFriend id="ctrlTAF" runat="server" />
  </td></tr>
</table>
<p>
This is some other content on the page that is unaffected
by the operation of the control.
...
</p>
</form>
</body>
</html>

Screen Capture

Here's a quick screen cap of the new control hosted within the host page:

Tell A Friend ASP.NET User Control

Download

You can download a zip file containing the files above as well as a copy of the original Tell a Friend ASP.NET sample for comparison from here: tell_a_friend_control.zip (3.5 Kb)


Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers