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

Beginning ASP.NET 2.0 With CSharp (2006) [eng]

.pdf
Скачиваний:
86
Добавлен:
16.08.2013
Размер:
20.33 Mб
Скачать

Chapter 10

Login Control (ASP.NET)

Link to ShoppingCart Control (User)

News Control (User)

Figure 10-16

 

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. 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.

368

Componentization

Figure 10-17

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

<%@ Page Language=”C#” Trace=”false” MasterPageFile=”~/site.master” AutoEventWireup=”true” codefile=”Default.aspx.cs” 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” %>

369

Chapter 10

You need to add a new tag specifying where the control will go on your page. It consists 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 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:

public void Page_Load( object sender, System.EventArgs e)

{

if (Page.IsPostBack)

{

if (TextBox1.Text == “42”)

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

else

{

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

}

}

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 you created in the chapter as a user control. You’ll see how you can place the user control in one web page, and then in 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.

370

Componentization

Figure 10-18

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

Figure 10-19

371

Chapter 10

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.cs:

public partial class SimpleUserControl : System.Web.UI.UserControl

{

protected void Page_Load(object sender, EventArgs e)

{

if (Page.IsPostBack)

{

if (TextBox1.Text == “42”)

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

{

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

}

}

}

}

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

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

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

7.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.

372

Componentization

Figure 10-20

Figure 10-21

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.

373

Chapter 10

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=”C#” AutoEventWireup=”false” CodeFile=”Default.aspx.cs” 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> </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 wanted 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.cs file themselves, and then every time the user control is called, it automatically uses the new code.

374

Componentization

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, 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 that 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.

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 check box is selected, as shown 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.

375

Chapter 10

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).

Figure 10-24

5.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>

6.Still in Source View, add the following to the SqlDataSource:

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

This contains the connection string information that you will need for this example.

7.Go to the code-behind file and add the following code for an ItemsToShow property, which governs how many items are shown on the screen at the same time:

376

Componentization

public partial class NewsUserControl : System.Web.UI.UserControl

{

private int _itemsToShow = 5; public int ItemsToShow

{

get

{

return _itemsToShow;

}

set

{

_itemsToShow = value;

}

}

8.Add the following code directly underneath the code you previously added:

private void Page_PreRender(object sender, System.EventArgs e)

{

string sel = string.Format(“SELECT Top {0} * FROM [News] WHERE DateToShow <= ‘{1}’ ORDER BY DateToShow DESC”, _itemsToShow, DateTime.Now.ToString(“yyyy/MM/dd”));

//Make sure above is all on one line. SqlDataSource1.SelectCommand = sel;

}

9.Go to Solution Explorer and create a new Web Form called NewsDisplay.aspx. Go to Design View and drag your NewsUserControl.ascx into the Web Form.

10.Run it — it’s fairly raw without any styles, but you will see five news items, as shown in Figure 10-25.

Figure 10-25

377