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

Real - World ASP .NET—Building a Content Management System - StephenR. G. Fraser

.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
4.59 Mб
Скачать

/// </summary>

private void InitializeComponent()

{

this.Load += new System.EventHandler (this.Page_Load);

}

#endregion

}

}

Wait a second, what DCViewer.cs file? It's not in the Solution Explorer. Well, actually it is, but it's hidden. There are three easy ways to view it:

§The first way is to click the Show All Files button in the Solution Explorer and then click the plus (+) symbol next to DCViewer.aspx. This method clutters up your Solution Explorer with a bunch of files that you care little about.

§The second method is to simply right-click the file DCViewer.aspx and then select View Code from the menu options.

§The third option is to select Code from the View menu or press F7 when DCViewer.aspx is the current file being edited.

The code is very simple. The first time that the WebForm1 is accessed, the OnInit event is triggered. This causes the OnInit() method to be called. This, in turn, calls the

InitializeComponent() method, which adds Page_Load() as the Load event so that every time the page is loaded it will be able to run. In some ASP.NET programs, the

InitializeComponent() method will add Page_Unload() as the Unload event so that every time the page is unloaded it will be run.

In the Page_Load() method, you will notice the IsPostBack variable. This handy variable enables the Page_Load() method to do something special the first time it is called (for example, load some intrinsic control with some information).

All ASP.NET Web pages have this basic shell (shown in Listing 6-2), except for the declarations of the intrinsic controls, of course, which are specific to each Web page:

protected System.Web.UI.WebControls.Label lbStory;

protected System.Web.UI.WebControls.Button bnGetStory;

protected System.Web.UI.WebControls.DropDownList ddlStories;

protected System.Web.UI.WebControls.TextBox tbNumber;

protected System.Web.UI.WebControls.TextBox tbUserName;

protected System.Web.UI.WebControls.TextBox tbName;

protected System.Web.UI.WebControls.RequiredFieldValidator rfvUserName;

You should know these controls because you created them when you changed their (ID) property. (For clarity, I took the liberty of removing the controls you didn't change.) Now that they are declared, you have complete control to do with them what you want, and you will do just that in a second.

Creating a Content Class

First, you need to create a helper class to store the vast amount of content that this viewer will provide (all three stories). The class is simple. It will store the headline and the story and will provide a constructor to load itself and two properties to extract the information.

1.Click Ch06Example in the Solution Explorer.

2.Select Add Class from the Project menu. This will create a dialog box similar to the one you see in Figure 6-7.

Figure 6-7: The Add New Item dialog box

3.Click the Web Project Items folder in the Categories window.

4.Click the Code folder under the Web Project Items folder.

5.Click the C# Class icon.

6.Enter Content.cs in the Name field.

7.Click Open.

Adding Properties and a Constructor to the Content Class

Normally, I would just go ahead and code the statements to add the property to the class, but this is a good opportunity to examine the Class View dialog box. You will use the dialog box to create the properties, but then you'll just go ahead and create the constructor the old-fashioned way, by typing three whole lines of code.

1.Select Class View from the View menu.

2.Click Ch06Example in the Class View dialog box.

3.Right -click the Content class.

4.Select Add Property from the Add menu item. This will create a dialog box similar to the one in Figure 6-8.

Figure 6-8: The C# Property Wizard

5.On the presented dialog box, set the following:

§Property Access: Public

§Property Type: String

§Property Name: Headline

§Accessors: get

§Property Modifiers: None

6.Click Finish.

7.Change the null in the Headline get statement to headline and add the headline variable, as shown in Listing 6-3 in the Content.cs

file.

Listing 6-3: Fix the Headline get Statement in Content.cs

protected string headline;

public string Headline

{

get

{

return headline;

}

}

8.Right -click the Content class.

9.Select Add Property from the Add menu item.

10.On the presented dialog box, set the following:

§Property Access: Public

§Property Type: String

§Property Name: Story

§Accessors: get

§Property Modifiers: None

11.Click Finish.

12.Change the null in the Story get statement to story and add the

story variable, as shown in Listing 6-4 in the Content.cs file.

Listing 6-4: Fix the Story get Statement in Content.cs

protected string story;

public string Story

{

get

{

return story;

}

}

13.Update the Content class constructor to initialize the headline and story, as shown in Listing 6-5.

Listing 6-5: Update the Content Constructor in Content.cs

public Content(string h, string s)

{

headline = h;

story = s;

}

When you have finished updating Content.cs, you should have a Content class that looks like Listing 6-6.

Listing 6-6: Content.cs

using System;

namespace Ch06Example

{

public class Content

{

protected string headline; protected string story;

public Content (string h, string s)

{

headline = h; story = s;

}

public string Headline

{

get

{

return headline;

}

}

public string Story

{

get

{

return story;

}

}

}

}

Declaring and Loading the Content Repository

Now that you have a class to store your content, albeit a very simple one, you can create an instance of it in WebForm1 in DCViewer.cs and then load it.

This example obviously is very simplified. I really don't recommend loading all of your stories in a huge array on your Web server as you are with the Dynamic Content Viewer. In fact, a simple array is not a good choice because normally the number of pieces of content in your system is a running target. It grows or shrinks based on what is created or removed by the content management application (CMA). A simple array works best when you know the number of elements that will make up the array and the number does not change too often.

An ArrayList might be a better choice because it can grow and shrink dynamically. More likely, you will store your content in a database (Chapter 7 covers this) or in an XML file or set of XML files (which Chapter 8 covers) and then retrieve them on demand. You will see in Chapter 13 that ASP.NET can cache the most common Web pages for you. Therefore, you don't have to worry about wasting time retrieving the same pages repeatedly from the dat abase or XML file(s).

1.Create a variable to store all of the stories by entering the highlighted text in Listing 6-7 into DCViewer.cs using the main edit window.

Listing 6-7: Declaring an Array of Stories

public class WebForm1 : System.Web.UI.Page

{

protected Content[] Stories = new Content[3]; protected System.Web.UI.WebControls.Label lbStory;

2.Load the stories into the Content array by entering the highlighted

text in Listing 6-8 into DCViewer.cs using the main edit window.

Listing 6-8: Loading the Array of Stories

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: This call is required by the ASP+ Windows Form Designer.

//

InitializeComponent();

Base.OnInit(e);

Stories[0] = new Content("New Hall of Fame Member",

"{0} joined the hockey hall of fame due to {1} MVP trophies."); Stories[1] = new Content("Hacker Located",

"{0} has been arrested on {1} accounts of bad coding."); Stories[2] = new Content("Lottery Winner",

"{0} said all {1} million in lottery winnings is going to charity.");

}

Filling the Drop-Down List from the Content Repository

It is time to fill in the drop-down list because you now have the headlines of the stories available. You can load a drop-down list in three different ways.

The first way is to use the intrinsic control <asp:ListItem>. This control is very

similar to the <OPTION> element of the <SELECT> list found in HTML. You could have hard-coded them directly into the ASPX file, as you did in Listing 6-8, but then the content viewer would not be very dynamic because the only way to change the dropdown list would be to go into the ASPX file and change the hard-coded

<asp:ListItem> values. Not that it is dynamic now—because you have hard-coded

the content in the code logic—but changing the logic to load in the stories from a file is much easier than continually changing the HTML.

Listing 6-9: Loading a Drop-Down List Using <asp:ListItem>

<tr>

<td>Select story:</td> <td>

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

<asp:ListItem Value="1">New Hall of Fame Member</asp:ListItem>

<asp:ListItem Value="2">Hacker Located</asp:ListItem>

<asp:ListItem Value="3">Lottery Winner</asp:ListItem>

</asp:DropDownList> </td>

</tr>

The second way to load a drop-down list is to use the DataSource property of the intrinsic control <asp:DropDownList>. It is fairly easy to implement; all you need to do is assign a class that implements the IEnumerable interface to the DataSource property. Sound tough? Ever heard of an array? An array implements the IEnumerable interface (arrays are actually an alias for System.Array classes), so all you have to do is assign an array to the DataSource and then call the DataBind() method of the drop-down list. Listing 6-10 shows how this can be done.

Listing 6-10: Loading a Drop-Down List Using the DataSource Property

protected string[] hlines = new string[]

{

"New Hall of Fame Member",

"Hacker Located",

"Lottery Winner"

};

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

{

if (!IsPostBack)

{

ddlStories.DataSource = hlines; ddlStories.DataBind();

}

}

 

 

Warning

If

 

yo

 

u

 

for

 

ge

 

t

 

to

 

ca

 

ll

 

th

 

e

 

D

 

at

 

a

 

Bi

 

nd

 

()

 

m

 

et

 

ho

 

d,

 

yo

 

ur

ar ra y is no t bo un d to th e dr op

-

do w n lis t an d th us yo ur dr op

-

do w n lis t wil l sti ll be e m pt y. (I kn o w be ca us e I pu lle d m y ha ir ou t

on thi s on e.)

The third way to load the drop-down list is the hardest way (which doesn't say much), and it is how I implemented it in the Dynamic Content Viewer. The technique is to enter one entry at a time using the Items property of the intrinsic control

<asp:DropDownList>.

This technique is the most powerful because it provides you the ability to do things such as add, remove, insert, and count the number of entries programmatically, thus providing the functionality needed to be dynamic. And, as you see in Listing 6-11, it is actually very easy to implement.

Listing 6-11: Loading a Drop-Down List Using the Items Property

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

{

if (!IsPostBack)

{

for (int i = 0; i < Stories.Length; i++)

{

ddlStories.Items.Add(Stories[i].Headline);

}

}

}

1.Select the View Class from View menu.

2.Expand the Ch06Example folder.

3.Expand the WebForm1 object.

4.Double-click the Page_Load() method.

5.Enter the highlighted text in Listing 6-11 using the edit window, which should now be positioned at the Page_Load() method.

Manipulating and Loading the Story for Viewing

You are almost done. All you need is a way to display the actual story selected. Because this is beyond easy, I decided to spice things up a bit and add a little fun personalization. You probably noticed the {0} and {1} in the stories loaded into the Stories array. If these don't mean anything to you, a little refresher course on string formatting using the String.Format() static method is in order.

The String.Format() method has the following basic format:

String.Format([format string], [substitute for marker {0}],

[substitute for marker {1}],

...,

[substitute for marker {n}]);

Formatting strings are made up of two parts: the constant string to be displayed and markers to display dynamic content. Any time you see a number surrounded by curly brackets, you have encountered a marker; anything else is the constant text. The

number in the curly brackets specifies which parameter following the format string to insert.

There is a lot more functionality available, but this is all you need to know for the current example. If you want to learn more about formatting, the online help is quite detailed. Now that you know how formatting of strings is done, I'm sure you can guess now that

{0} is a marker for tbUserName and {1} is for tbNumber.

All that's left to do to complete the Dynamic Content Viewer are the following two steps:

1.Position the cursor in the main edit window.

2.Enter the highlighted text in Listing 6-12.

Listing 6-12: Displaying the Selected Story Using a Label

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

{

if (!IsPostBack)

{

...

}

else

{

lbStory.Text = String.Format(Stories[ddlStories.SelectedIndex].Story,

tbUserName.Text, tbNumber.Text);

}

}

I used a little trick to figure out which story to display. It just so happens that the SelectedIndex property of the ddlStories drop-down list is also zero-based like the Stories array. When I loaded the ddlStories drop-down list, I had to make sure I retained the same index order as the Stories array.

A safer way would be to store, in the ddlStories drop-down list, the value of the index to the Stories array corresponding to the Headline loaded. Listing 6-13 shows how it would look if you were to do it this way.

Listing 6-13: Displaying the Selected Story Using a Label

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

{

if (!IsPostBack)

{

for (int i = 0; i < Stories.Length; i++)

{

ddlStories.Items.Add(new ListItem(Stories[i].Headline, i.ToString()));

}

}

else

{

Соседние файлы в предмете Программирование