Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
20
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Componentization

14.From the Data Section of the Toolbox, drag an ObjectDataSource control where the

SqlDataSource used to be.

15.Click the black arrow at the top right of the ObjectDataSource control, and from the Common Tasks menu select Configure Data Source.

16.In the opening dialog select wroxunitedTableAdapters.PlayersTableAdapter and click Next.

17.In the Select tab pick the “GetPlayers(Int32 PlayerID), returns PlayersDataTablemethod is selected from the drop-down list box and click Next.

18.In the Define Parameters dialog select “Control” from the Parameter Source: dropdown list box and select GridView1 in Control view. The parameters on the left of the dialog will now show GridView.SelectedValue. Click Finish.

19.Right-click the ObjectDataSource control in Design View and select Properties.

20.In the Properties window change the (ID) property so that it reads “DetailsDataSource”.

21.Open EditSquad.aspx.vb and amend code in the procedure parameters to read as follows in the following three subs:

Sub DetailsDataSource_Updated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs )

...

End Sub

Sub DetailsDataSource_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs )

...

End Sub

Sub DetailsDataSource_Deleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs )

...

End Sub

22.Save and close the file.

23.Run the application, log in as an administrator (dave\dave@123), and navigate to the EditSquad.aspx page. It works in the same way as before except that you are now using an

ObjectDataSource control.

How It Works

You haven’t changed much between this and the previous example. You built a data component, and you then added an ObjectDataSource control into the EditSquad.aspx page. You added methods for the Update, Insert, and Delete methods via the wizard. The code that provided your functionality in the classes was already in existence; all you had to do was change the references from the SqlDataSource control to the ObjectDataSource control. Then you ran it, and the WroxUnited application was able to use the ObjectDataSource instead.

369

Chapter 10

User Controls

Your final problem is that of making your code easy to reuse, and this is addressed by user controls. Again, these are something that existed in ASP.NET 1.x, but this is something that also has been improved upon in ASP.NET 2.0. So what are user controls? Well in a nutshell, user controls are reusable Web Forms. They’ve been through several name changes and evolutions from scriptlets to pagelets, before arriving at user controls. They can be thought of as mini-scripts or mini-pages, or pages within your pages, but however you choose to think of them the key is that they can be called up as many times as you need them.

If you browse the Wrox United site you can see several examples of user controls, and one, the News control, is visible on the front page. In fact, if you look at the front page (shown in Figure 10-16), it is a multitude of components garnered from different sources.

Login Control (ASP.NET)

Link to ShoppingCart Control (User)

News Control (User)

Figure 10-16

 

370

Componentization

The News control is a user control, the Login control is an ASP.NET control, the shopping cart is a link to a user control, and the menu is derived from the site master, which itself is an ASP.NET control. So the entire site front page and design is reusable. If you click the Shopping Cart link, you will see the second user control, shown in Figure 10-17.

Figure 10-17

And there are a couple more in the administrative section of the site too, but you get the idea! The idea is that these controls can be used in multiple pages, or called from different places, and rather than having to cut and paste the code individually each time, you can just call on this one section of code over and over again. One question that might be on your lips is how do they differ from the normal ASP.NET server controls, such as the TextBox control or the Login control that you looked at earlier?

Very little is the answer. The main difference is that you have to provide the code behind the control yourself, whereas ASP.NET server controls come fully working out of the box. You can add properties to user controls and set them as attributes, just like you would with a normal ASP.NET server control.

So why isn’t everything an ASP.NET server control? Well, ASP.NET 2.0 ships with a multitude of controls designed for the most common scenarios and situations. ASP.NET 2.0 adds greatly to the number of server controls. For example, in ASP.NET 1.1 if you wanted a Login control you had to stitch together a username text box, a password text box, a button, and a label for messages within a panel, so you had to create this as a user control. In version 2.0, the Login control comes as a server control. However, it just isn’t possible to anticipate everything that a user might want or need. So therefore it makes sense to have the flexibility to create your own.

If you view the source code in Internet Explorer for the home page (Default.aspx) in WroxUnited.net, you’ll see no indication that a user control has been used; it’s all HTML elements and some occasional script, which is just as it should be. If you were using a Flash plug-in or a Java applet, you would see some indication with an <object> tag or on older browsers possibly an <embed> tag. So there’s no worry about extra download time being taken either.

371

Chapter 10

If you look at the actual page that is sent to the server, you can see the user control is included with a simple two lines of code that we’ve highlighted (this source code page is available for download at www.wrox.com):

<%@ Page Language=”VB” MasterPageFile=”~/site.master” AutoEventWireup=”false” codefile=”Default.aspx.vb” Inherits=”_Default” %>

<%@ Register TagPrefix=”uc1” TagName=”News” Src=”News.ascx” %>

<asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”server”>

<h2>Welcome to the Wrox United Web site.</h2>

<p>We’re a great football team. No really, we are. Don’t take any notice of our past performance. We’re just unlucky.</p>

<uc1:news id=”News1” runat=”server” ItemsToShow=”3”></uc1:news>

</asp:Content>

This page starts giving you some clues as to how user controls work.

User Control Structure

User controls are stored in separate files with a separate .ascx extension. Any time you see this extension you know that you are dealing with a user control. To create a user control you need to add a @Register directive to the top of your Web Form identifying where you can find your user control:

<%@Register TagPrefix=”WroxUnited” TagName=”MyControl” %>

You need to add a new tag specifying where the control will go on your page. It will be composed of the TagPrefix, followed by a colon, followed by the TagName, an ID, and the now familiar runat=server attribute:

<WroxUnited:MyControl id=”mycontrol1” runat=”server”>

</WroxUnited:MyControl>

Lastly, you need to specify the user control itself in a separate .ascx file. Unlike Web Forms, you don’t need to specify extra <html> and <body> tags, because the contents of this control will be added to the body of the containing main page. In fact, all you need to have is the controls themselves that you want to include. For example, you could include the controls from the code-behind example used earlier in the chapter:

<asp:Label ID=”Label1” runat=”server” Text=”What is the answer to the meaning of life, the universe and everything?:”></asp:Label>

<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox> <br /><br />

<asp:Button ID=”Button1” runat=”server” Text=”Submit” /> <br />

<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>

Of course, user controls can have code-behind files as well, just like Web Forms:

372

Componentization

Sub Page Load()

If (Page.IsPostBack) Then

If TextBox1.Text = “42” Then

Label2.Text = “So you read Douglas Adams as well...”

Else

Label2.Text = “No, I’m not sure that’s it”

End If

End If

End Sub

This control can then be bolted into your web pages wherever you specify the @Register directive and add a tag for the control.

A Simple User Control

In the next Try It Out, you’re going to start by creating a trivial “Hello World”-style user control to get you used to the idea of including them in your pages. This code does no more than encapsulate the code behind from the first example we created in the chapter as a user control. You’ll see how you can place the user control in one web page, and then a second web page.

Try It Out

Creating a Simple User Control

1.Open VWD and create a new ASP.NET web site called SimpleUserControl in the chapter directory (C:\BegASPNET\Chapters\Begin\Chapter10).

2.In Solution Explorer, right-click the web site and select Add New Item. Select Web User Control, enter the name SimpleUserControl.ascx, and check the Place Code in Separate File option, as shown in Figure 10-18.

Figure 10-18

373

Chapter 10

3.Now you need to add the controls to the page. Once again, drag two Label controls, a TextBox control, and a Button control, as shown in Figure 10-19.

Figure 10-19

You can cut and paste the relevant code from the first Try It Out in this chapter into Source View if you still have it at hand:

<asp:Label ID=”Label1” runat=”server” Text=”What is the answer to the meaning of life, the universe and everything?:”></asp:Label>

<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox> <br /><br />

<asp:Button ID=”Button1” runat=”server” Text=”Submit” /> <br />

<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>

4.Double-click the page again and this time add the following code-behind to

SimpleUserControl.ascx.vb:

Partial Class SimpleUserControl

374

Componentization

Inherits System.Web.UI.UserControl

Sub Page Load()

If (Page.IsPostBack) Then

If TextBox1.Text = “42” Then

Label2.Text = “So you read Douglas Adams as well...”

Else

Label2.Text = “No, I’m not sure that’s it”

End If

End If

End Sub

End Class

5.Next you need to add this control to a page. From Solution Explorer drag the

SimpleControlUser.ascx into Design View for Default.aspx (see Figure 10-20).

Figure 10-20

6.Click the green arrow to run Default.aspx; it works in exactly the same way as it did in the first Try It Out of this chapter, as evidenced in Figure 10-21.

375

Chapter 10

Figure 10-21

7.Now go to Solution Explorer and right-click the project. Select Add New Item and add a new Web Form to the page called secondpage.aspx.

8.Go to Design View and drag SimpleUserControl.ascx into this page. Next, go to Solution Explorer and right-click secondpage.aspx and select Set As Start Page.

9.Run the project again. You should see what appears in Figure 10-22. Your control has been successfully duplicated with no extra lines of code being required.

Figure 10-22

How It Works

This hopefully shows you just how easy it is to reuse code in your pages. If you go to Default.aspx and view the source you will see the following:

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>

<% Register Src=”SimpleUserControl.ascx” TagPrefix=”uc1”

TagName=”SimpleUserControl” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”>

<title>Untitled Page</title>

376

Componentization

</head>

<body>

<form id=”form1” runat=”server”> <div>

<uc1:SimpleUserControl id=”SimpleUserControl1 runat=”server” /> </div>

</form>

</body>

</html>

The highlighted lines of code are the only two lines that have been added to the original source code. The first registers the user control and specifies a tag prefix of uc1 (short for user control one) and a TagName of SimpleUserControl. The control is then inserted into the page along with an id attribute and a runat=server attribute.

There’s nothing to stop you from copying this tag and pasting it again and again in the page, although it might make your page a little illogical, with several versions of the user control. Note that this example got you to cut and paste the old code from the code-behind page. This was quite deliberate because this was the old way of transferring replicated code. Each time you want to transfer the code, you would cut and paste it manually. Not only is cutting and pasting more labor-intensive, but it is also far more prone to mistakes, because if you altered the code in one page, it would need to be altered in all of the rest. With user controls, any changes you need to make can just be made to the .ascx file and the .ascx.vb file themselves, and then every time the user control is called, it automatically uses the new code.

The Wrox United News User Control

You’re now going to move onto a more complex user control, and one that is used on the Wrox United web site. You’re going to re-create the News control that you find on the main Wrox United site. This control scans the News table and selects the most up-to-date stories and displays them on the front page, with the most recent being displayed first.

Before you launch into the coding, it’s worth saying a little bit about why we chose to make this a user control, while other bits and pieces we chose not to. A News control is something that is going to be common on many web sites (although technically speaking user controls shouldn’t be used across several applications — as you will see at the end of this chapter — because there is something better served for t hat purpose). It is also something that will quite likely be called upon at several places throughout the application (although you only call upon it once within the Wrox United application), and the principle will remain the same throughout; it will display a list of articles in order, with the most recent first. Of course, not all things you will design on this site will be suitable for reuse and for creating as user controls, but the News control is a content delivery mechanism and content is the driving force behind most web sites. In the following Try It Out, you create your own News user control and drop it into your own blank page.

Try It Out

Using the News Control

1.Open Visual Web Developer and select Open Web Site. From the Chapter10 folder (C:\BegASPNET\Chapters\Begin\Chapter10), select WroxUnitedNewsControl and click OK. This contains the connection string information that you will need for this example.

377

Chapter 10

2.Go to Visual Web Developer and right-click the top item in Solution Explorer. Select Add New Item and select Web User Control. Type NewsUserControl.ascx in the Name text box. Make sure the Place Code in Separate File checkbox is selected, as depicted in Figure 10-23.

Figure 10-23

3.Go to Design View and drag a SqlDataSource control from the Data section of the Toolbox menu. Don’t, however, click to configure the Data Source from the Common Tasks box that appears. Instead, switch to source view, and add the following to the SqlDataSource:

ConnectionString=”<%$ConnectionStrings:WroxUnited%>”

4.From the Data section of the Toolbox menu, add a Repeater control below the SqlDataSource and select SqlDataSource1 to be the Repeater’s Data Source (see Figure 10-24).

5.First we’ll add the template to the HTML. With the Repeater control you have to switch to Source View to add the template. Switch to Source View and add the following code:

<asp:Repeater ID=”Repeater1” Runat=”server” DataSourceID=”SqlDataSource1”> <ItemTemplate>

<div class=”newsItem”>

<span class=”newsDate”><%#Eval(“DateToShow”, “{0:dd MMM yyyy}”)%> </span>

<span class=”newsTitle”><%#Eval(“Title”)%></span>

</div>

<span class=”newsContent”> <%#Eval(“Description”) %>

</span>

</ItemTemplate>

</asp:Repeater>

378