1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 6 ppt

90 281 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 6 ppt
Trường học Wrox
Chuyên ngành ASP.NET Development
Thể loại sách hướng dẫn
Năm xuất bản 2003
Thành phố Unknown
Định dạng
Số trang 90
Dung lượng 1,68 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

This chapter will look at two specific ways of using components in ASP.NET: ❑ User control: A Web form that is encapsulated in a reusable server control ❑ Code-behind: Used for separatin

Trang 2

6. First, change the DayRenderevent handler as follows (remove the original style settings andreplace them with a single class statement):

public void EventCalendar_DayRender(object sender, DayRenderEventArgs e)

// The following line will exist in your code if you completed the

// exercises at the end of the last chapter

7. Change the code for the calendar in the HTMLview:

<asp:Calendar id="EventCalendar" runat="server"

OnSelectionChanged="EventCalendar_SelectionChanged"

OnDayRender="EventCalendar_DayRender" CssClass="calendar">

<DayStyle cssclass="normaldate"></DayStyle>

<OtherMonthDayStyle cssclass="othermonthdate"></OtherMonthDayStyle>

Trang 4

12. It's about time to run the page and try it out for yourself! The first style you'll see is the Homestyle page, as shown in Figure 11-19, the away kit that is shown in Figure 11-20, is fairly

different, as you’ll no doubt notice!

Trang 5

Figure 11-19:

Figure 11-20

Trang 6

13. If you check the Remember Preferencebox before clicking Apply, the style you are applying will

be remembered for you in a cookie Next time you open the site, this stylesheet will be thedefault

The next step was to add some controls to the page to select and apply the stylesheet to the page:

<hr /><br/><br/>

<p>

Choose a theme: <br/>

<asp:DropDownList id="ddlTheme" runat="server">

<asp:ListItem Value="WroxUnited.css" Selected="true">

void btnApplyTheme_Click(object sender, EventArgs e)

{

Session["SelectedCss"] = ddlTheme.SelectedItem.Value;

Set the value of the session to be the value of the currently selected drop down list item (not the

displayed text) This value is the filename for the stylesheet

Trang 7

OK, so you have a session and a cookie – the next stage is to read those values in when the page isloaded:

public void Page_Load(object sender, EventArgs e)

public void EventCalendar_DayRender(object sender, DayRenderEventArgs e){

Trang 8

We covered quite a bit of ground in this chapter We used cookies, sessions, and applications and cacheddata for enhancing performance We also had some fun with interactive examples in this chapter thatdemonstrated these concepts

The important points covered in this chapter are:

❑ Cookies are a neat way to store small pieces of identifying data, but cannot be relied upon (usersmay have them disabled in their browser preferences)

❑ Sessions are an extremely powerful way to store data that exists for as long as a user is

connected to the site, and you can use them to store data for online shopping examples

❑ Application-scope objects are accessible by any page in an application and are a great way tocentralize objects that need to be shared

❑ Caching data is crucial to improving application performance, but it's also similar to storingdata in the Applicationobject However, the Cacheobject has some neat features such as

Trang 9

linking to a dependency, and you can control when items in the cache expire and react to theevents raised when those items expire.

The next chapter will look at encapsulating commonly used page elements into reusable sections known

as user controls You'll also learn how the code-behind technique can be used to cleanly separate HTMLcode from C# code

Exercises

1. Add the text, Current Topic, and a label control to the Chat.aspxpage above the main chat boxthat contains the text of the current topic (stored in the Applicationobject) Add some defaulttopic text to the Global.asaxfile, and also another box and button to the page, allowing you tochange the current topic

2. Add the session initialization code from the Stylesheet example to your Global.asaxfile

3. Add a link to the Merchandise.aspxpage from the front page of the site, then apply thestylesheet used in the Default.aspxpage to all the other pages in the site You will need toadd the <link >tag to the <head >section of each page, and you will need to ensurethat the session initialization code is correctly configured in the Global.asaxfile from theprevious exercises

Trang 10

Reusable Code for ASP.NET

So far, most of the ASP.NET pages we've built were quite specialized and self-contained We've put

a lot of functionality into each page, but only retained the benefits of our hard work from one page

to another by copying the entire contents into a new ASPX page

This isn't an ideal way to write functionality-rich Web sites, particularly if you're on a salary andexpected to deliver results before the next millennium! We'll now look at writing reusable code forASP.NET Note that we're not just talking about objects here (although, yet again, objects play a

crucial role in the reusability story), but about code components – totally independent files that

encapsulate groups of useful functionality

This chapter will look at two specific ways of using components in ASP.NET:

User control: A Web form that is encapsulated in a reusable server control

Code-behind: Used for separating HTML user interface design (color, aesthetics, and soon) from page code

First, let's take a careful look at what is meant by components and consider the various advantagesthey offer

Encapsulation

As discussed in Chapter 7, an object essentially is a software construct that bundles together data

and functionality You can define interfaces to use the functionality that an object contains, forexample, by creating methods and properties that can be accessed programmatically

By hiding everything that doesn't concern task-specific usage of an object, implementation detailsare hidden from the consumer, which makes it a lot easier to robustly plug an object together withother objects This makes it far easier for large teams of developers to build complex applicationsthat don't fall prey to lots of low-level weaknesses

Trang 11

Crucial information about an object is held in its class definition, and any code with access to this classshould be able to instantiate an instance of this class and store it in an object The way in which the

object works is encapsulated, so that only the public methods and properties are available to the

consumers of the class

In a similar way, a code component is reusable code stored in a location that is accessible to manyapplications Like an object, it encapsulates functionality, but while an object is an implementation unit,

a component is a deployment or packaging unit A component could be a single class or could holdmultiple class definitions Figure 12-1 considers a quick example:

Figure 12-1

The first ASP.NET page creates a new object of type Class1 that resides within the Component1

component The second ASP.NET page creates two new objects – one of type Class1 and one of typeClass2 Class2 also resides within Component1

All code written so far has been held in specific ASPX pages So, what's the point in having all thisreusable code if it can only be reached from within a single page? We need to break our reusable codeinto separate components that we can reference from other ASPX pages

A component packages a set of classes and interfaces to isolate and encapsulate a specific functionality,

and can provide a well-specified set of publicly available services It is designed for a specific purpose rather than for a specific application.

Components

A component is a self-contained unit of functionality with external interfaces that are independent of itsinternal architecture In other words, it is code packaged as a black box that can be used in as manydifferent applications as required

Trang 12

Microsoft Windows is an example of componentization If you spend a lot of time working with

Windows, you're almost certain to have come across Dynamic Link Libraries (DLL) files These files

contain components that define most of the functionality that you're likely to come across in Windows,including that of any applications you've installed

For example, every time you start an instance of Internet Explorer, you're actually running a smallprogram called iexplore.exe This program accesses numerous DLLs that reside in your systemdirectory (C:\WinNTor C:\Windows), and most of the browser's functionality is defined within thesefiles This directory also contains the Explorer.exe file, which is the executable for Windows Explorer.Note that both these applications feature an identical Addressbar, where you type in the URL of a Website or the path to a local directory This user interface element has been implemented once and

packaged inside a component, so that it can now be used by both programs

What's more, if you enter the URL for a Web page in the Windows Explorer address bar, you can viewthat page and even browse the Web in the main pane without having to use iexplore.exeat all.Likewise, you can use iexplore.exeto view and browse your files by entering a file path in theaddress bar

What we can deduce from this is that either there's a lot of duplication between the two executable files,

or that the two sets of browser functionality are actually implemented as standalone components thatcan be accessed by both applications

Another case to consider is the Microsoft Office suite, which features many components that are sharedamong individual Office applications, as also throughout Windows For example, there is a componentthat handles the Save Asdialog used by Word, Excel, Outlook, and the rest – this is why the Save Asdialog looks the same, no matter which application you run it from This component is actually aWindows component and the Office package uses it whenever you save or load a file You can also usethis from any other application that lets you save or load files, for example, Internet Explorer or evenMicrosoft Notepad as shown in Figure 12-2:

Figure 12-2

Trang 13

This component probably includes some presentation code for the buttons and code logic that governswhat happens when you click on each of these buttons For example, changing the selection in the Saveoption in dropdown box changes the files listed in the main window to show the contents of the selecteddirectory.

Throughout this book, the aspnet_isapicomponent has been working away behind IIS to process all

of our ASP.NET pages When IIS detects a request for a page with a aspxextension, it uses this

component to process the page and communicate with the NET Framework

DLLs are classified as system files and are hidden by default They can only be seen in Windows

Explorer if the 'Show hidden files and folders' option in your Folder Options is set The DLLs talked

about in these examples are COM DLLs .NET DLLs differ slightly in what they contain and the

underlying technology, but the concept of componentization used is the same.

Why Use Components?

You should start thinking of components as small, self-contained nuggets of functionality that canpotentially make life a lot simpler when building any sort of non-trivial application In components,behind-the-scenes functionality is encapsulated so that only certain specific interfaces are available to theprogrammer It can contain class definitions that specify which objects can be created and which onescan be used for behind-the-scenes code The benefits of using components include:

❑ An individual component is a lot simpler than a fully-blown application It is restricted to a set

of predefined functionality

❑ As components are self-contained, they can be seamlessly upgraded (or fixed) simply by replacing one component with another that supports the same interfaces (methods, properties,and so on)

❑ Since using components is a good way of dividing your application into serviceable chunks,sometimes the functionality of a component might be reusable in other applications You couldeven make it available to other programmers, or incorporate some of their components intoyour applications

Ultimately, components reduce the amount of code you write and make your code easier to maintain.Moreover, you can even obtain components from third party component vendors, which is a verypopular way to enhance the functionality of ASP.NET sites For example, if you need components thatutilize the drawing capabilities of NET to their limit, and your existing knowledge does not cover this,you can consider looking for a third-party solution that you can bolt onto your application

Applying Component Theory to Applications

Let's look at how componentization relates to our application models So far in this book, we've madeASP.NET pages that do all sorts of things ranging from working with information input via a form toconnecting to a database and working with data Throughout the book, you've been encouraged to keepyour code separated into distinct blocks – the dynamically generated content (ASP.NET code) andpresentation (HTML and various controls) – so that it's easy to change the look of your page withoutaffecting what it does Web Matrix simplifies this process with its separate HTMLand Codeviews

Trang 14

In addition, we've written a lot of C# code in our pages for accessing and working with data stored in acentral database C# provides a framework of logical operations between the data and presentation code.Let's consider an example Imagine a team of developers creating a Web site that sells books Some ofthese developers would be concerned with the look, feel, and usability of the site They'd be responsiblefor the public image of the company on the Web, so they'd be more concerned about design, color, andusability This group will include designers who probably use HTML and graphics tools such as

Macromedia Flash for fancy loading screens Another set of developers would be mainly interested inproviding nifty blocks of code that do cool things, such as such as validating the information enteredinto a form by the customers when they click a button These developers would also be responsible forgenerating the code required to connect to the database of different books and preparing information onindividual titles for display on the site The designers would then make use of that information anddisplay it in an aesthetically pleasing fashion

If you were to constantly use ASP.NET pages that had all of the code and HTML on the same page, itwould be awkward for both sets of people to work on the site at once Simple mistakes could easily bemade if people overwrote each other's code In addition, every page would have to be hand-made, andcode would have to be copied, pasted, and amended as appropriate If you made one change to thefunctionality of your site, you'd have to remember to make that change to all the appropriate pages.However, if you could separate out the HTML and design-focused code from the ASP.NET code blocks,and then reuse bits of that code, it would be much easier to update a single piece of code to changefunctionality – every page that used it would be automatically updated

This style of work would make everyone happy – Web designers get to play with color and layout asmuch as they like, and the ASP.NET developers can fine-tune their code without affecting the look andfeel of the site Code separation and reuse implies that the designers and developers can work in

parallel, allowing applications to be developed much more quickly This is called Rapid Application Development.

This chapter will look at two ways of dividing code into reusable sections – user controls and code-behind

files In the next chapter, we'll take this one step further and look at compiled components and customserver controls

Let's look at user controls, the first application of this code-separation concept

User Controls

When the ASP.NET team first devised the concept of user controls, they were called pagelets, a term that

many people disliked They were later renamed, but many felt that pagelet, or a mini-page, was a gooddescriptive term for these controls

User controls are Web forms encapsulated into a reusable control They hold blocks of code that arerepetitively required by many pages in a Web site For example, consider the Microsoft Web site whereeach page has the same header style – a menu bar and a logo This is a common feature for many Websites; our own http://www.wrox.com/shown in Figure 12-3 has this kind of style, for example:

Trang 15

Figure 12-3

The Wrox site has the same kinds of menu bars visible on the screen at all times These panes, panels, orframes (depending on what you call them and how you code them) form just one example of what usercontrols can provide

Instead of having to copy and paste chunks of repeated code to provide the header on all of our pages,

we can create a simple user control that will have this code inside it, ready to be used It's a way of

accessing the same functionality repeatedly throughout an application

If you've ever programmed with ASP 3.0, you'll probably be familiar with include files User controls

are similar to these files, but because ASP.NET is different from ASP 3.0, these controls are now created and used in a different manner, and include advanced features such as caching (covered in Chapter 11).

User controls can also do a lot more than simply produce headers and footers We can give these controlsthe ability to look and function like ASP.NET Server controls We can code properties so that the controlcan adapt according to its set attributes A user control can be used repetitively on a site when manypages have similar blocks of functionality Take, for example, a user login control This control could becreated as a user control by using a couple of textboxes and labels

Another example is a menu control that applies different formatting to a page link if the page is

currently being viewed, or displays a submenu for that page A user control is saved with a ascxfileextension, and can be called from any of the ASP.NET pages in our application by using just two lines ofcode The main principle of user controls is that you essentially cut out a portion of code from your

Trang 16

ASP.NET page and paste it into a user control, where it will work just fine as long as the ASP.NET pageknows where to find the code and where to put it.

Let's look at a few pros and cons of using user controls in your applications User controls are ideal for:

❑ Using repetitive elements (such as headers, menus, login controls, and so on) on pages

❑ Reducing the amount of code per page by encapsulating repetitive elements

❑ Improving page performance by using caching functionality available to user controls forfrequently viewed

However, some situations aren't ideal for using user controls These include:

❑ Separation of presentation HTML from the code blocks (use code-behind, discussed later in thischapter)

❑ Encapsulation of data access methods in a reusable package (use pre-compiled assemblies,discussed in the next chapter)

❑ Creating a control that can be reused more widely than in just your application (use customserver controls, discussed in the next chapter)

It's time to start looking at code This chapter and the next will look at creating custom reusable elements

in ASP.NET pages, showing how these elements can all be plugged together with minimal fuss, toproduce a very clean aspxfile by hiding advanced functionality within reusable components The nextexample demonstrates user controls in action.In this example, we will discuss a very basic example (toshow the theory), which will be followed by a more complex example We'll add a simple header control

to the default page of the Wrox United application

Try It Out Our First User Control

1. Start by creating a new ASP.NET user control within the Wrox United folder as shown in Figure12-4 and name it SimpleHeader.ascx(note the different file extension – ascx, not aspx):

Figure 12-4

Trang 17

2. In the new file, switch to HTMLview – notice that there is hardly anything in the file when it'sfirst created! All you need to do here is add one line of code:

<h1>Wrox United</h1>

3. Save this file and reopen Default.aspxfrom the Wrox United application We'll replace theheading in this page with the newly created user control To do this, Switch to Allview – noticethe yellow highlighted lines (which aren't visible in any other view) at the top of the file This iswhere you need to add the first piece of code Add the following highlighted line of code:

Trang 18

7. It's time to try it out – run the page and you should see the familiar front page of the site asshown in Figure 12-6:

Figure 12-6

Notice that the front page looks the same as before, and the new title has the correct style applied to it as

if it were still a part of the main page

How It Works

Having completed this example, you won't see any difference in the rendered page when it is run andthe page that we built in the last chapter However, the technique that we implemented behind thescenes (changing the hard-coded HTML to a reusable control) can prove to be very useful, as you'll seefor yourself later in this chapter

If you open up SimpleHeader.ascxin the Allview in Web Matrix, you'll see the following:

Trang 19

The default code that Web Matrix added is quite light There are a couple of comments, an unused scriptblock, and a special directive at the top of the code The first line of code tells the compiler that we wrotethis control in C# The only code added to the page was the <h1>Wrox United</h1>line This line ofcode can be displayed on any code that uses this control.Let's look at the 'consumer' of our ASCX usercontrol, the Default.aspx page:

<WroxUnited:SimpleHeader id="HeaderControl" runat="server"/>

Here you can see the WroxUnited:SimpleHeadersyntax discussed earlier The control is added to thepage using the TagNameand TagPrefixspecified in the attribute declaration at the top of the page.Web Matrix can provide a preview of pages that include user controls, so you could see the output of theuser control that you have added in Designview The result is that the page is rendered in exactly thesame way as before The HTML code from the control is rendered within the HTML of the page

While this user control could be implemented on every page in the site easily, this isn't exactly the mostexciting control that we could use Let's work on a visually appealing header control that can be

displayed at the top of every page in the site.Let's create a user control that forms a header for the WroxUnited Web site Our example used a few images, including a team logo and pictures of the players.These images are available for download, along with the rest of the code for the book, from

http://www.wrox.com/

Try It Out Wrox United – Header Control

1. Open up Web Matrix and create a new ASP.NET user control called header.ascx Enter thefollowing code in the HTMLview:

<table width="100%">

Trang 20

<tr style="BACKGROUND-IMAGE: url(images/headbg.gif);"><td>

<table width="800">

<tr style="VERTICAL-ALIGN: middle">

<td style="TEXT-ALIGN: left" width="200">

<a href="default.aspx"><img src="images/logo.gif" border="0"></a>

</td>

<td style="TEXT-ALIGN: center" width="400">

<img src="images/teamlogo.gif" />

</td>

<td style="TEXT-ALIGN: right" width="200">

<asp:AdRotator id="AdRotator1" runat="server"

2. Switch to Codeview and enter the following line of text:

public string PageTitle = "";""

3. Save this file as header.ascx You'll notice an ASP.NET AdRotatorcontrol in this file Thiscontrol depends on the contents of an XML file Let's create this by creating a new blank XMLpage called faces.xmland adding the following code to it:

Trang 21

<%@ Register TagPrefix="WroxUnited" TagName="Header" Src="header.ascx" %>

6. Change the code that embeds the header control in the page as follows:

Trang 22

How It Works

In this example, we implemented another simple user control and introduced the AdRotatorcontrol.This control is traditionally used to store banner advertisements and rotate the visible advertisementaccording to a random algorithm Each time the page is refreshed, an advertisement is selected fordisplay The frequency with which each advert appears on the page depends on the weightage we give

to each advertisement In this example, each ad is given equal weightage so adverts display for equalintervals of time but in a random fashion whenever the page is refreshed

In this example, the AdRotatorcontrol was used to display images of the members of the team (instead

of displaying ads) and to change the image on subsequent visits to the site The information that controlswhich images to display and how often to display them is stored in an XML file

Let's break down the code and work through what we did First, the header.ascxcontrol:

<table width="100%">

<tr style="BACKGROUND-IMAGE: url(images/headbg.gif);"><td>

<table width="800">

<tr style="VERTICAL-ALIGN: middle">

<td style="TEXT-ALIGN: left" width="200">

<a href="default.aspx"><img src="images/logo.gif" border="0"></a>

</td>

<td style="TEXT-ALIGN: center" width="400">

<img src="images/teamlogo.gif" />

</td>

<td style="TEXT-ALIGN: right" width="200">

<asp:AdRotator id="AdRotator1" runat="server"

of the header The contents of the row were centered along a horizontal axis:

<tr style="VERTICAL-ALIGN: middle">

Then, each of the three cells were aligned to the left, center, or right of the vertical axis of each cellrespectively:

<td style="TEXT-ALIGN: left" width="200">

In the first two cells, a couple of static images were added Notice that the image in the first cell iswrapped in an HTML anchor (<A >) tag, which will turn the image into a hyperlink In this case,clicking the first image would take the user to the front page, thus making it a handy 'home' button thatusers can use to return to the default page

Trang 23

In the third cell, we added an AdRotatorcontrol:

<asp:AdRotator id="AdRotator1" runat="server"

Height="95px" Width="100px"

AdvertisementFile="faces.xml"></asp:AdRotator>

The control declaration is very simple, but the most interesting part is the link to the

AdvertisementFileXML file, which controls how AdRotatorworks Let's look at an extract of thatfile:

<AlternateText>Player: Chris Hart</AlternateText>

The <Impressions>tag controls the weightage that affects how often this advertisement (or image) isdisplayed as compared to other advertisements In this example, all players have equal weighting, butyou could indicate a preference for your favorite player by increasing the number for that particularimage element:

Trang 24

The last tag controls the keyword for the advert This element is optional, but you can use it to filteradvertisements by including a KeywordFilterattribute to the <ASP:AdRotator >tag in yourASP.NET pages:

<Keyword>ChrisH</Keyword>

The last piece of the puzzle involves including this header on the Default.aspxpage You only need tomake a couple of minor changes (including adding a directive at the top of the page) to specify that youwant to use the new header file in the page:

<%@ Register TagPrefix="WroxUnited" TagName="Header" Src="Header.ascx" %>You can then use the control in the page by including the following line of code:

<WroxUnited:Header id="HeaderControl" runat="server"></WroxUnited:Header>Before we move on, don't forget that you could include this header control on all the pages of the WroxUnited site in the same way With this in mind, we added an interactive element to this header control.Recall the last line in the Headercontrol itself:

<h2><%= PageTitle %></h2>

This line of text will create a Heading 2 style paragraph, and add the text contents of the PageTitlepublic variable to the page:

public string PageTitle = "";""

Take the Chat application as an example; add two lines of code to the Chat.aspxpage to see this inaction (assuming that you've already added code to add the selected CSS theme to the page) First, at thetop of the page, add the following:

<%@ Register TagPrefix="WroxUnited" TagName="Header" Src="Header.ascx" %>Then add the following tag (instead of the Heading 1 and 2 tags) to the HTMLview of the page:

<form runat="server">

<WroxUnited:Header id="HeaderControl" runat="server" PageTitle="Online Chat"></WroxUnited:Header>

<asp:TextBox id="txtChatBox" runat="server" TextMode="MultiLine"

Height="200px" Width="550px" ReadOnly="true"></asp:TextBox>When you view this page in your browser, it should appear as shown in Figure 12-8:

Keep the total of all the values in the <Impressions> tags under 2 billion to avoid a

runtime error.

Trang 25

Figure 12-8

Heading 2 text has been included on the page, thanks to the PageTitleattribute in the control's declaration This is a neat trick for making header controls a bit more interactive, removing standardcode from the main pages, and also ensuring that the look and feel of all pages is maintained centrally.Let's look at a slightly different type of user control This control can be used as a navigation bar, like thelinks on the left of the front page An advantage is that it can be added to all the pages in the site withminimal code reuse

Try It Out Wrox United – Navigation User Control

In this example, we will take the ASP.NET hyperlink controls from Default.aspxalong with the associated code from the left-hand side of the page and place it in a user control

1. Create a new user control called Navbar.ascxand add the following code:

<div class="navbar">

</div>

We will add code between these tags in just a moment

Trang 26

2. Reopen Default.aspxand head straight to the Allview Add the following highlighted line ofcode to the top of the page:

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

<%@ Register TagPrefix="WroxUnited" TagName="Header" Src="Header.ascx" %>

<%@ Register TagPrefix="WroxUnited" TagName="NavBar" Src="NavBar.ascx" %>

3. Back in HTMLview, find the section that contains code pertaining to the left hand column ofhyperlinks (the first <td>element in the big layout table) This column contains the links andthe CSS selector Copy this section and paste it into Navbar.ascxwithin the <div>tag:

<asp:DropDownList id="ddlTheme" runat="server">

<asp:ListItem Value="WroxUnited.css" Selected="true">Home

Trang 27

4. Now replace the original left hand column of the main layout table in Default.aspxwith thefollowing:

<table style="WIDTH: 800px">

<tr>

<td style="VERTICAL-ALIGN: top; WIDTH: 200px">

<WroxUnited:NavBar id="NavigationLinks" runat="server">

In the last part of this Try-It-Out, we'll add some styling to the control We don't have a

stylesheet declaration in the code for this control, but that's not a problem Once a control is

added to a page, the control will inherit the current stylesheet information from the parent

Trang 28

Figure 12-9

8. Add the control to the Chat.aspxpage in exactly the same way as before First, add the following line to the top of the page:

<%@ Register TagPrefix="WroxUnited" TagName="NavBar" Src="NavBar.ascx" %>

9. Then add the navigation bar control to the page Note, however, that you need to add a layouttable to make space for this control:

Trang 29

<asp:Button id="btnClearLog" onclick="btnClearLog_Click"

runat="server" Text="Clear log"></asp:Button>

Just like in the previous examples, to add a user control to a page, you include two extra lines in the.aspxpage:

Trang 30

<%@ Register TagPrefix="WroxUnited" TagName="NavBar" Src="NavBar.ascx" %>

<WroxUnited:NavBar id="NavigationBar" runat="server"></WroxUnited:NavBar>

In our example, the code in the ASP.NET user control also contained an event handler that was takenfrom Default.aspx This event handler is run whenever the button in the user control is clicked Itchanges in the same way as the stylesheet used on the page, on every page that includes the control Thisholds true as long as each of these pages contains a stylesheet reference in the HTMLview of the page:

<link id="css" href='<%= (string)Session["SelectedCss"] %>' type="text/css"rel="stylesheet" />

If you completed the exercises at the end of the previous chapter, you'll already have this statement atthe top of each of the pages in the site

We're now going to move on to code-behind and how to neatly separate our code into separate,

manageable sections

Code-Behind

When we were creating simple forms in Chapter 3, we simply created textboxes and worked with

buttons that sent data on a round trip to the server To enhance these forms, we added code that handledvalidating input, and so on The extra code that enabled validation in small functions was put at thebottom of our pages to avoid cluttering the presentation code However, there is a cleaner way of doing

this – move all of this code into a code-behind file.

A code-behind file can be used to store all of the script blocks of an ASP.NET page While it's perfectlypossible to include this in the same page as the presentation HTML code, separating out the script blocks

is a good way to separate presentation from the code All the presentation code remains in one ASPXfile(or, if you've got a couple of user controls for repetitive presentation elements, it can partly reside inASCXfiles), and the code-behind code lives in a language-specific file For example, a csfile is a C#code-behind file, and a vbfile is a Visual Basic NET code-behind file The ASPXfile is the central pointfor the application from which the code-behind file and any user controls are referenced

Code-behind files are easy to deploy – all you need to do is copy over the code-behind file along withthe ASPXpage You can even compile your code-behind files into an assembly to reuse the functionalitycontained within them over more than one page or application In the next chapter, we'll introducecompilation You'll learn how to compile components and why this is a useful technique to employ inyour applications

A code-behind file can be written in any NET-compatible language, some good examples being C#(which we've used throughout this book so far), VB.NET, and JScript NET This concept will be explored

in the next chapter, when we talk about NET assemblies – don't worry if you haven't got any

experience with the other languages, as we'll stick with C# for the rest of this book

In Visual Studio NET, Web Forms applications are always created with a code-behind file, rather than placing code

on the same page In addition, code-behind files in Visual Studio NET are named the same as the ASPX page, with

Trang 31

an additional cs or vb on the end of the filename For example, MyPage.aspx would have an associated C# code-behind page named MyPage.aspx.cs.

Let's look at a simple example of a code-behind file In this example we're going to create a very simpleWeb Form with a textbox and a button, and give this simple arrangement extra functionality by adding acode-behind file

Try It Out Our First Code-Behind File

1. In Web Matrix, create a new C# class file and call it SimpleCodeBehind.cs Set the class name

to MyCodeBehindand the namespace to Wroxas shown in Figure 12-11:

Trang 32

}

This basic code contains many comments to help you to place code in the file correctly Let'slook at the file without comments for a moment to make it a bit clearer to see what we've got:namespace Wrox

public TextBox Name;

public Label Message;

public void SubmitBtn_Click(object sender, EventArgs e)

Trang 33

The public MyCodeBehind()method is a constructor, a type of method used when creating a class.However, we don't need this method in a code-behind file.

6. Create a new ASP.NET page called SimpleCodeBehind.aspx, and save it in the same directory

as the code-behind page Switch to the Allview and add the following code:

<%@ Page Language="C#" Inherits="Wrox.MyCodeBehind" Src="SimpleCodeBehind.cs"

Please enter your name then click the button below:<br /> <br />

<asp:textbox id="Name" runat="Server" />

<asp:button text="ClickMe!" OnClick="SubmitBtn_Click" runat="server" />

<%@ Page Inherits="Wrox.MyCodeBehind" Src="SimpleCodeBehind.cs" %>

This line of code is essential when working with code-behind The first part of the statement specifiesthat we will be using the functionality in the MyCodeBehindclass, which is a member of the Wrox

Trang 34

namespace The page will inherit the functionality defined in the MyCodeBehindclass (refer to Chapter 7

for more information on inheritance) The second part of this statement specifies where to find the class– in this case, in the SimpleCodeBehind.csfile Only one of these declarations can be used for anygiven ASPXpage

The rest of this ASP.NET page is simple with a textbox, a button, and a Labelcontrol These controls

are the same as the ones introduced in Chapter 3:

<form runat="server">

Please enter your name then click the button below:<br /> <br />

<asp:textbox id="Name" runat="Server" />

<asp:button text="ClickMe!" OnClick="SubmitBtn_Click" runat="server" />

see this because it's all done behind the scenes As mentioned in Chapter 7, these namespaces provide

easy access to the classes they contain To make use of one of their classes, you can simply refer to theclass by name instead of typing out the full path that includes all of the namespace

The next line of code assigns a Namespaceand names the class in the code-behind file If you remember,the first line in our ASP.NET page mentioned Wrox.MyCodeBehind Well, this is what the ASP.NET page

is looking for – the MyCodeBehindclass in the Wroxnamespace

public TextBox Name;

public Label Message;

Trang 35

These lines are simply variable declarations and mimic the names of the controls on the ASP.NET page.You need to use this technique for any code-behind file – all controls on a page that you want interactingwith the code-behind file need to have a corresponding local variable.

public void SubmitBtn_Click(object sender, EventArgs e)

be changed to display the welcome message that is constructed whenever the button is clicked

This example was very simple, and it didn't really show off the benefits of using code-behind to thefullest However, it did illustrate the principle of encapsulation This technique can be used to

encapsulate a lot of logic to deal with user input, thereby separating the jobs of the designer and theprogrammer, which is one of the goals of ASP.NET

Code behind can be used on any ASPX page with a <script >block on it The code portion of thepage can be cleanly moved out to the code-behind file

If you use or intend to use Visual Studio NET, you will notice that this is the default behavior Using

code-behind is good practice since it neatly separates presentation from code – using it outside of the

Visual Studio NET environment is optional but is still a good idea.

The key steps to remember when switching to using code-behind are:

❑ Reference the code-behind file from your ASPX page by using the single line at the top of thepage, specifying the class that the ASPX page is inheriting from, and the source file that containsthat class definition

❑ In the code-behind file, ensure to add : Pageon the same line as the class definition, after thename of the class

❑ Again, in the code-behind file, add variable declarations corresponding to each of the controls

on the page that you will be working with programmatically Ensure that you make eachvariable Publicin scope

❑ Finally, in the code-behind file, enter the code that formerly resided in the script block on theASPX page Ensure that all the essential Importsstatements are added at the top of the page toreference the appropriate class libraries so that the code runs as intended

It's worth noting that the principle of code-behind can be applied to user controls in exactly the samemanner as to normal ASPX pages All you need to do is add a statement to the top of the ASCX control,with the same syntax that the ASPX statement used in the preceding example, to link the ascxto anassociated ascx.cscode-behind file

Trang 36

Let's try using code-behind in the Wrox United site In the next example, we'll look at how we couldseparate the script code contained in the Default.aspxpage into a separate file.

Try It Out Using Code-Behind in Wrox United

1. Create a new class file called Default.aspx.cswith a namespace of WroxUnited, and a classname of DefaultCodeBehind

2. In this file, you will need to copy over all the lines of code from the Codeview of

Default.aspx These are mostly methods and one public hashtable These lines are nothighlighted in the following listing (we've not included all the code from the methods in thislisting; just their signatures, to give you an idea how many methods we're moving) The

highlighted lines below need to be added to the code-behind page to make it work:

public TextBox txtEmailAddress;

public Label lblRegister;

public Button btnRegister;

public Panel pnlFixtureDetails;

public Repeater MatchesByDateList;

public Calendar EventCalendar;

Trang 37

Notice that all the methods are marked as public.

3. Once you've created the code-behind page, save the file Ensure that you have removed all codefrom the Codeview of the Default.aspxpage, and then add the following line to the top ofthe page while in the Allview:

<%@ Page Inherits="WroxUnited.DefaultCodeBehind" Src="Default.aspx.cs"

Trang 38

namespace WroxUnited

{

public class DefaultCodeBehind : Page

{

public TextBox txtEmailAddress;

public Label lblRegister;

public Button btnRegister;

public Panel pnlFixtureDetails;

public Repeater MatchesByDateList;

public Calendar EventCalendar;

Well, for creating Web applications a natural progression is to switch to Visual Studio NET from WebMatrix Visual Studio NET uses code-behind by default Using code-behind is also good practice if youhave multiple developers working on an application, because it forces you to keep presentation codeseparate from functionality code, leaving you with cleaner and more understandable code

These two methods are relatively straightforward, and simply involve moving code into different areas

to improve readability, reduce complexity, and reduce errors caused by mixing presentation and script.The next chapter will look at more advanced methods of encapsulating code functionality into reusablecomponents, namely NET assemblies and custom server controls

Exercises

1. Add the header control and navigation bar control to each page in the site Remember to addthe following code at the top of each page:

Trang 39

<%@ Register TagPrefix="WroxUnited" TagName="Header" Src="Header.ascx" %>

<%@ Register TagPrefix="WroxUnited" TagName="NavBar" Src="NavBar.ascx" %>

2. Move the C# code for each page (visible in the Codeview in Web Matrix) into an associatedcode-behind file, making sure each control has a corresponding declaration in the code-behindfile Note that the Players.aspx page will be a bit more tricky Firstly, you will need to create afolder (if it doesn't already exist) within your WroxUnited directory called bin Into thisdirectory, you need to copy the following file: C:\Program Files\Microsoft ASP.NET WebMatrix\v0.6.812\Framework\Microsoft.Matrix.Framework.dll

This file contains the code that the guys at Microsoft provided for you to use if you want todeploy any of the Web Matrix custom controls, like the MxDataGridthat we used in theprevious chapters You'll learn more about dllfiles and the bindirectory in the next chapter

3. Move the C# code from the navbar.ascxcontrol (which contains an event handler) into anassociated ascx.cscode-behind file, following exactly the same technique that you used forthe other pages on the site

4. Create a user control for the Merchandise.aspxpage that enables you to easily add new items

to the list You will need to copy a row of the table from Merchandise.aspxinto a new ASCXuser control file Make the properties on the image and button controls generic, then add somepublic properties to programmatically set the values on each web control in the user control.Here's some code to get you started Firstly, here's some code that is currently in

Merchandise.aspxthat could be placed in the control:

to construct the appropriate values for these attributes:

private string _itemName = "";

public string ItemName

{

get{return _itemName;}

set{_itemName = value;}

}

Trang 40

Here's an example of using this property to update another private variable:

if (_imageName == "")

{

_imageName = _itemName & ".jpg";

}

This could be used, for example, to provide a default image name

You would also need to move the AddItemToBasketmethod to the control because the buttonsnow reside within this control Since the name of the session is globally available, it's possible toset or update session values from the control just as easily as from a page

You will need three properties in all The first, ItemNameis shown in the preceding code Youcan include an optional property, to override the default value (in case you want to use a gif, forexample) Finally, you need to store the text that describes the item in a Textproperty, andinclude the value stored in this property in the page using the following syntax:

<td><%=Text%></td>

All that remains then is to add the item to the page:

<WroxUnited:Product id="Shirt" runat="server"

ItemName="Shirt"

ImageName="shirt.gif"

Text="The Wrox United shirt, available in one size only"/>

5. Move the new code in Product.ascxinto a code-behind file

Ngày đăng: 13/08/2014, 04:21

TỪ KHÓA LIÊN QUAN