350 likes | 433 Views
CSC209 Web Programming. Chapter 8 – User Controls Dr. Stephanos Mavromoustakos. Chapter Overview. Besides the master pages, themes, and skins discussed in Chapter 6 you can also use User Controls to create reusable and consistent blocks of information.
E N D
CSC209 Web Programming Chapter 8 – User Controls Dr. Stephanos Mavromoustakos
Chapter Overview Besides the master pages, themes, and skins discussed in Chapter 6 you can also use User Controls to create reusable and consistent blocks of information. A user control is a sort of mini ASPX page in that it has a markup section and optionally a Code Behind file. This chapter will cover: • What are user controls and how do they look? • How do you create user controls? • How do you consume user controls in your page? • How can you improve the usefulness of user controls by adding coding logic to them?
Introduction to User Controls While master pages allow you to create content that is displayed in all pages in your site, it’s common to have content that should only appear on some but not all pages. For example, you may want to display a banner on a few popular pages only. Without user controls, you would add the code for the banner to each page that needs it. • User controls have an .ascx extension instead .aspx • User controls cannot be requested in the browser directly. You need to add it to a page
Practice – Creating a User Control You will create a vertical banner. For this exercise you will need 2 images that represent banners – one in portrait mode (about 120x240 pixels) and one in landscape mode (about 486x60). In C:\BegASPNet\source\Chapter 8\Images you will find these 2 banners, or you can create your own. • Open your project • If you haven’t done so already, create a folder called Controls in the root of the site • Create also a folder called Images in the root of the site • Using Windows Explorer go to the Image folder and drag the 2 banners into the Images folder in VWD.
Practice – Creating a User Control • Right-click the Controls folder and choose Add New Item. Click the Web User Control. Name the file Banner.ascx and the click Add to add the control to the site
Practice – Creating a User Control • Switch the user control to Design View and then drag a Panel from the Standard category of the Toolbox onto the design surface. Change its ID property to pnlVertical • Drag an Image control into the Panel. Locate the ImageUrl property and click the ellipses button. Browse to the Images folder, select the banner120x240.gif image, and click OK to add it to the user control • Also, locate the AlternateText property and type This is a sample banner • Switch to Markup View and if your Panel has Height and Width attributes, remove them
Practice – Creating a User Control • Change the code to the following: <%@ Control Language="VB" AutoEventWireup="false" CodeFile="Banner.ascx.vb" Inherits="Controls_Banner" %> <asp:Panel ID="pnlVertical" runat="server"> <a href="http://p2p.wrox.com" target="_blank"> <asp:Image ID="Image1" runat="server" AlternateText="This is a sample banner" ImageUrl="~/Images/Banner120x240.gif" /> </a> </asp:Panel>
Adding User Controls to a Content Page or Master Page To use a user control you need two steps: • To register the control by adding an @ Register directive to the page or control where you want the user control to appear. • To add the tags for the user control to the page and optionally setting some attributes on it When the control is registered, you can add it to the page using the tagprefix:tagname construct, similar to the way you add standard server controls to a page.
Practice – Adding the User Control to your Page You will add the user control Banner.ascx to the master page, so it displays a banner on each page in the site in the sidebar area. • Open up MasterPage.master from the MasterPages folder and switch it into Design View • Locate the drop-down list that shows the themes, position your cursor right after that, and press Enter three times to create some room • From the Solution Explorer, drag the file Banner.ascx into the empty spot you just created • Design view is updated and not looks like this:
Practice – Adding the User Control to your Page • Switch to Markup View and locate the @ Register directive at the top of the file. Change the two dots in the src attribute to (~): <%@ Register src="~/Controls/Banner.ascx" tagname="Banner" tagprefix="uc1" %> • Save the changes, close it and then right-click the file Default.aspx in the root of your site and choose View in Browser • The banner is now displayed below the drop-down list. Switch to other theme and you’ll see the same banner. When you click the banner, it takes you to the site you specified. • If you wanted to remove the border from linked images you can use the following CSS: img { border: none; }
Practice – Registering User Controls in the web.config File In this exercise, you will register the Banner.ascx user control in the web.config file. • Open the web.config file from the root of your site • Scroll down a bit and locate the <pages> element • Add the following code as a child to the <controls> element that you find under <pages> add tagPrefix="Wrox" tagName="Banner" src="~/Controls/Banner.ascx" /> • Save the changes and close the file • Open the master page again in Markup View and locate the Banner control in the sidebar area. Change the ucl to Wrox: <Wrox:Banner ID="Banner1" runat="server" /> • Scroll all the way up in the master page file and remove the entire line with the @ Register directive • Save and close the file • Open Default.aspx again in your browser. Note that the banner is still there.
Creating your own Data Types for Properties You can add a second image to the control that displays as a horizontal banner. By adding a property to the user control you can then determine whether to display the vertical or horizontal image. You should do this by creating a numeric property of type System.Byte. Then 0 would be vertical and 1 would be horizontal for example. Since this is difficult to remember what it represents, you can create a String property that accepts the values Horizontal and Vertical. However, strings cannot be checked at development time, so you may end up with a spelling mistake, resulting in an error or in the incorrect banner being displayed. Instead, you can create your own data type in the form of an enumeration.
Creating your own Data Types for Properties With an enumeration (or enum), you assign numbers to human friendly text strings. Developers then use this readable text, while under the hood the numeric value is used. The following snippet shows a basic example of an enum: Public Enum Direction Horizontal Vertical End Enum With these enums, the compiler assigns numeric values to the Horizontal and Vertical members automatically, starting with 0 and counting upward. You can also explicitly define your numeric values if you want:
Creating your own Data Types for Properties Public Enum Direction Horizontal = 0 Vertical = 1 End Enum • The cool thing about enums is that you will get IntelliSense in code files, in the Properties Grid and even in the code editor for your user controls. • Just as with other code files like classes, you should put your enums in a file under the App_Code folder. • If you have more than one of them you can store them all in the same file or create a separate file for each enum. • Enums are great for simple and short lists.
Practice – Creating Smarter User Controls In this exercise, you add a second banner to the user control. To avoid the two banners from showing up at the same time you will add a property that determines which banner to display. Pages that use the control can then define the correct banner. • Start by creating an enum of Vertical and Horizontal. To do this, right-click the App_Code folder and choose Add New Item. Add a class file called Direction. • Write the following code: Public Enum Direction Horizontal Vertical End Enum • Save and close the file
Practice – Creating Smarter User Controls • Open the Code Behind of Banner.ascx and add the following property. To help you create this property, VWD comes with a handy code snippet. Type Property and press Tab. You can press Tab again to move from field to field. Partial Class Controls_Banner Inherits System.Web.UI.UserControl Private _displayDirection As Direction Public Property DisplayDirection() As Direction Get Return _displayDirection End Get Set(ByVal value As Direction) _displayDirection = value End Set End Property End Class
Practice – Creating Smarter User Controls • Open the Markup View of Banner.ascx, copy the entire <asp:panel>, and paste it right below the existing Panel. Name the Panel pnlHorizontal and set the src of the image to ~/Images/Banner468x60.gif <asp:Panel ID="pnlHorizontal" runat="server"> <a href="http://p2p.wrox.com" target="_blank"> <asp:Image ID="Image2" runat="server" AlternateText="This is a sample banner" ImageUrl="~/Images/Banner468x60.gif" /> </a> </asp:Panel> • Switch back to Code Behind of the control and add the following code to the Page_Load handler. To do this, choose (PageEvents) from the left drop-down list at the top of the Document Window and Load from the right drop-down list.
Practice – Creating Smarter User Controls Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load pnlHorizontal.Visible = False pnlVertical.Visible = False Select Case DisplayDirection Case Direction.Horizontal pnlHorizontal.Visible = True Case Direction.Vertical pnlVertical.Visible = True End Select End Sub • Save and close the two files for now
Practice – Creating Smarter User Controls • Open up the master page file in Markup View and locate the user control declaration. Right after the runat=“server” add the following DisplayDirection attribute that sets the correct image type <Wrox:Banner ID="Banner1" runat="server" DisplayDirection=“Horizontal" /> • Save all changes and request the page Default.aspx in the browser. Note that the right sidebar area now contains the horizontal image which is too wide. • Switch back to the master page and change the DisplayDirection from Horizontal to Vertical. Save your changes and refresh the page in the browser. The sidebar should now displays the vertical banner
Practice – Creating Smarter User Controls • Open the page AboutUs.aspx from the About folder in Markup View. In the cpMainContentContentPlaceHolder add some text, like below: <asp:Content ID="Content2" ContentPlaceHolderID="cpMainContent" Runat="Server"> This is our Class exercise site. What a Wonderful Site!!!<br /> </asp:Content> • Switch to Design View and drop the Banner.ascx control from the Solution Explorer onto the design surface, right below the text you just added.
Practice – Creating Smarter User Controls • Select the control in Design View, open its Properties Grid and set the DisplayDirection to Horizontal
Practice – Creating Smarter User Controls • Save all your changes and then press Ctrl+F5 to open the About Us page in your browser. Besides the banner in the right, you should also see the horizontal banner appear in the content area
Implementing ViewState Properties • Besides the DisplayDirection, another useful property for the user control would be the URL that the banner links to. • To be able to set the URL that a user is taken to from code, you need to be able to access the anchor tag that is defined in the control’s markup. To do this, you need to give it an ID and a runat=“server” attribute. Alternatively, you could change the simple <a> tag to its server-side counterpart: the <asp:Hyperlink>. • To be able to set the new NavigateUrl property programmatically and to ensure it survives postbaks, you’ll implement a ViewState property. • To show you why you need a ViewState property, the first three steps of the next exercise have you modify the About Us page so it sets the DisplayDirection of the Banner control programmatically. You’ll then cause a postback to appear so you can see that the value for the direction gets lost because it doesn’t maintain its state in ViewState. • The second part of the exercise then shows you how to implement the NavigateUrl property that is able to maintain its state.
Practice – Implementing the NavigateUrl Property • Open the Code Behind of AboutUs.aspx and add the following code to the Page_Load event. If the handler isn’t there yet, you can double-click on the grey area of the page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Banner1.DisplayDirection = Direction.Vertical End If End Sub Verify that the Banner user control has an ID of Banner1 (it could be Banner 2 in your case) in the Markup View of the page, or update your code accordingly
Practice – Implementing the NavigateUrl Property • Switch to Design View and add a Button control by dragging it on top of the Banner.ascx control. It should end up above or below the banner. • Save the page and open it in your browser. Because of the code in Page_Load, the first time the page loads, the banner at the bottom of the screen displays the vertical banner. Now click the button so the page will reload. This page displays the horizontal image. Because the DisplayDirection of the Banner control is only set in Page_Load when Page.IsPostBack is False, that setting is lost when you post back, causing the banner to revert to its default setting of Horizontal
Practice – Implementing the NavigateUrl Property • To avoid this problem with the NavigateUrl, you need to implement it as a ViewState property. Instead of a simple backing variable used with the DisplayDirection property, you use the ViewState collection as the backing store. That way, the value is stored in ViewState and sent to the browser and back to the server with every request. To implement the property, add the following code to the Code Behind of the Banner.ascx user control, right below the DisplayDirection property:
Practice – Implementing the NavigateUrl Property Public Property NavigateUrl() As String Get Dim _navigateUrl As Object = ViewState("NavigateUrl") If _navigateUrlIsNot Nothing Then Return CType(_navigateUrl, String) Else Return "http://p2p.wrox.com" End If End Get Set(ByVal value As String) ViewState("navigateUrl") = Value End Set End Property
Practice – Implementing the NavigateUrl Property • Switch to Markup View of the user control and add a runat=“server” attribute to both the links. Give the link in the vertical panel an ID of lnkVertical and the other an ID of lnkHorizontal <asp:Panel ID="pnlVertical" runat="server"> <a href="http://p2p.wrox.com" target="_blank" runat="server" id="lnkVertical"> <asp:Image ID="Image1" runat="server" AlternateText="This is a sample banner" ImageUrl="~/Images/Banner120x240.gif" /> </a> </asp:Panel> <asp:Panel ID="pnlHorizontal" runat="server"> <a href="http://p2p.wrox.com" target="_blank" runat="server" id="lnkHorizontal"> <asp:Image ID="Image2" runat="server" AlternateText="This is a sample banner" ImageUrl="~/Images/Banner468x60.gif" /> </a> </asp:Panel>
Practice – Implementing the NavigateUrl Property • Switch back to the Code Behind of the user control and modify the Page_Load handler of the user control so it also sets the HRef property of the anchor element: Select Case DisplayDirection Case Direction.Horizontal pnlHorizontal.Visible = True lnkHorizontal.HRef = NavigateUrl Case Direction.Vertical pnlVertical.Visible = True lnkVertical.HRef = NavigateUrl End Select
Practice – Implementing the NavigateUrl Property • Save the changes and go back to the Code Behind of AboutUs.aspx. Modify the code so it sets the NavigationUrl property of the Banner control to a different URL. You should overwrite the code that sets the DisplayDirection Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Banner2.NavigateUrl = "http://imar.spaanjaars.com" End If End Sub
Practice – Implementing the NavigateUrl Property • Save all your changes and before request the AboutUs.aspx page in the browser close all browsers first. Click the horizontal banner at the left of the page. A new window will popup, showing the URL you set in the previous step. • Close the new window and click the button you added to About.aspx earlier to cause the page to post back to the server. Once the page is reloaded, click the banner image again. You are taken to the same site as in the previous step. This illustrates the point that the NavigateUrl property is now able to maintain its value across postbacks, unlike the DisplayDirection property you added to the user control earlier.