202

19
Introduction Welcome back! Today we're going to continue our exploration of ASP.NET. And this is an exciting day, because we'll be using Visual Web Developer to create a real, live ASP.NET Web program. It will definitely be fun. In this real, live program, we'll create a Web page that includes a text box where the user of your Web page can fill in some information, and a button whereby the user can send the data back to your Web server. As you work through today's lesson, please keep in mind what we covered in Lesson 1, about the difference between the client and the server. Remember, you're writing a program that runs on the server. People sitting at a computer can use their Web browser to look at a Web page created by your server. That page will have a place where they can type in some information and click a button. When they do so, what they typed will get sent back to your server program. Your server program can then read what the user typed and then create a new Web page to send back to the user. If that sounds complicated, don't sweat it, because it really isn't. In Chapter 2, we'll look at some screen captures that show what your program will look like when it runs in the browser. Then you'll see how simple it is. Before we get started, I want to make a quick comment about languages. When you use Visual Web Developer, you can use either C# or VB.NET to create your server programs. For this course, if you're familiar and comfortable with C#, then feel free to use it. But if you don't already know C#, please use VB.NET. It's a bit easier. Note: Throughout this course, you'll see code snippets presented in boxes. These are interactive boxes, and you can simply click on the scroll bar on the bottom of the box and slide it to the right to view all of the code. If you want to print the code snippet, simply click the Print code link above each snippet box. Creating a Form By the end of this chapter, you'll have a Web page that looks like this:

description

http://msdongieux.110mb.com/Lesson%202.pdf

Transcript of 202

Page 1: 202

Introduction Welcome back! Today we're going to continue our exploration of ASP.NET. And this is an exciting day,

because we'll be using Visual Web Developer to create a real, live ASP.NET Web program. It will

definitely be fun.

In this real, live program, we'll create a Web page that includes a text box where the user of your Web

page can fill in some information, and a button whereby the user can send the data back to your Web

server.

As you work through today's lesson, please keep in mind what we covered in Lesson 1, about the

difference between the client and the server. Remember, you're writing a program that runs on the

server. People sitting at a computer can use their Web browser to look at a Web page created by your

server. That page will have a place where they can type in some information and click a button. When

they do so, what they typed will get sent back to your server program. Your server program can then

read what the user typed and then create a new Web page to send back to the user.

If that sounds complicated, don't sweat it, because it really isn't. In Chapter 2, we'll look at some screen

captures that show what your program will look like when it runs in the browser. Then you'll see how

simple it is.

Before we get started, I want to make a quick comment about languages. When you use Visual Web

Developer, you can use either C# or VB.NET to create your server programs. For this course, if you're

familiar and comfortable with C#, then feel free to use it. But if you don't already know C#, please use

VB.NET. It's a bit easier.

Note: Throughout this course, you'll see code snippets presented in

boxes. These are interactive boxes, and you can simply click on the

scroll bar on the bottom of the box and slide it to the right to view all of

the code. If you want to print the code snippet, simply click the Print

code link above each snippet box.

Creating a Form By the end of this chapter, you'll have a Web page that looks like this:

Page 2: 202

A form with a text box and button

When you type a name into the text box in this Web page and click the button, you'll get back another

Web page that looks like this:

The form that appears after button is clicked

Page 3: 202

Creating a Folder for This Lesson Before creating the form, you probably want to organize your project in VWD. So, let's create a folder

for this lesson's project. We'll do this for all our lesson projects. First, go ahead and open Visual Web

Developer if you haven't done so already, and also open the myweb project that you created in Lesson

1.

Now, go over to the Solution Explorer, and right-click the name of the solution shown at the

top,C:\myweb. A pop-up menu will appear. Choose New Folder.

Choose new folder in the pop-up menu

A folder will appear, as shown here, and you will be able to type a name into it. Please type Lesson2.

Page 4: 202

Create a Lesson2 folder

Note:

If you accidentally click outside of the edit area and the folder gets the automatic name,

NewFolder1, simply right-click the folder, and in the pop-up menu, chooseRename.

This folder will hold the Web pages you'll build in today's lesson. Now let's make that first page!

A Page With a Button and Text Box In the picture above, you saw that your first Web page today will have a text box and a button. In ASP-

speak, the official names of these items are TextBox and Button (note the capital letters and lack of

spaces).

Let's go ahead and create that form. You want to make sure the form ends up in the right place inside

your Web server. We're going to put it in the Lesson2 folder that you just created. To get it in the right

place, right-click the Lesson 2 folder in the Solution Explorer, and in the pop-up menu choose Add New

Item.

Page 5: 202

Choose Add New Item

The Add New Item window will open. Choose Web Form in the upper-left corner. In the Name box,

typemyname.aspx. (Make sure you include the .aspx part. That's the only way the Web server will know

your page is an ASP.NET page.) For language, choose Visual Basic, unless you prefer C#. Leave the two

check boxes unchecked, and click the Add button.

The Add New Item window

Page 6: 202

After you click the Add button, you'll see your new page opened in the left part of the window, and

you'll see your page's name in the Solution Explorer.

Your page has been created

Note:

If your page's name is under C:\myweb instead of in the Lesson2 folder, simply click the

name and drag it on top of the Lesson 2 folder. That will move it. (After dragging, you

might have to click the + symbol to the left of the Lesson 2 folder to see your page.)

Way in the lower-left part of the window, click the Design button. (There might be a pause as VWD does

some thinking the first time you do this.) Type the following into the design window:

Hello and welcome to my Web site! What is your name?

Press ENTER at the end of the line. Next, find the tab Toolbox in the lower-right corner of the window,

and click it to open the Toolbox. Inside the Toolbox, make sure the Standard folder is expanded. (In

other words, if you see a + sign to the left of the name Standard, click the +.) Under Standard, find

TextBox (it should be the third item down). Click TextBox, and drag it over to your Design window,

dropping it just below the text that you typed, so your form looks like this:

Page 7: 202

The text and new TextBox

Next, do the same thing to create a button. To do so, find Button in the Toolbox (it should be the fourth

item down). Click it, and without letting go of your mouse, drag it over to your Design window, dropping

it just to the right of your TextBox. Your page will now look like this:

Now the button is there

You're almost done! Now you're going to change the text that's on the button. Right now, it just

saysButton. That's boring, So let's change it now.

Make sure the button in your design window is selected. How do you know it's selected? Look back at

the image above. Do you see how there are some little square boxes on its right side, bottom side, and

lower-right corner? Those are handles that you can use to resize the button. But the fact that they're

present means the button is selected. (Notice the text box doesn't have any.)

The button should be selected in your designer, but if instead you see the boxes on the text box, simply

single-click the button.

(Don't double-click it. If you do, you'll automatically go to the Source view, and you'll end up with some

code that you don't want. If this happens, click the Edit > Undo menu to remove the code that was

created. Then highlight the OnClick="Button1_Click" that you see toward the middle, and delete it by

pressing DELETE, making sure to leave a space between the double quote and the word Text. Then click

Page 8: 202

the Design button in the lower left of the screen to get back to the Design view. Then once again, single-

click the button that you created.)

Now, with the button selected, click the Properties tab in the lower right of the window to open the

Properties window.

The Properties window

The Properties window shows various things about the selected item, in this case the button. Notice the

item called Text, which is highlighted in the preceding image. This lets you specify the words that appear

on the button. To the right of the word Text, double-click the word Button. The word should get

highlighted. Press BACKSPACE to get rid of the text that's already there, and type the word Okay.

Now press ENTER. Look back at the Design view. You'll see that the text changed on the button. Pretty

good!

Now save your work. I prefer to just press CTRL + S. But, if you prefer, you can click File > Save

Lesson2/myname.aspx.

The first part of the form is ready. If you like, you can run the form in a browser. Doing so is easy; just

press CTRL + F5 (or click Debug > Start Without Debugging. You'll see the form open in your browser,

looking pretty much identical to the way it looks in your Designer. Your page won't do anything yet if

you click the button—that's coming up next.

Your first step is done, and you're well on your way to having your first dynamic Web page!

Make Your Form Smart

Page 9: 202

In this chapter, you're going to be typing some real, live code. If you're familiar with VB.NET or C#, then

you'll be free to explore things a bit further than what I describe here. But if you're not, then fear not;

we'll look at some VB.NET code and go through exactly what it does.

Make sure you have the myname.aspx file open in VWD (the file you created in the previous chapter).

Then click the Source button in the lower left of the window to switch to source view if you're not

already there. Here's what you should see:

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

Hello and welcome to my Web site! What is your name?<br />

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:Button ID="Button1" runat="server" Text="Okay" /></div>

</form>

</body>

Page 10: 202

</html>

Your version might be spaced a little differently or have some lines broken up onto two separate lines.

That's not a problem.

Now look closely in between the div tags. Notice the text you typed earlier:

Hello and welcome to my Web site! What is your name?

Also notice that the text is followed by a br tag. That's because you pressed ENTER after you typed the

text. Now look at what's on the next couple of lines. The first is a special ASP.NET tag that tells the Web

server to create a text box. The tag is <asp:TextBox>. You see, each ASP.NET tag gets its own identifier.

Let me explain why.

Think about this: You might have more than one text box tag on a page. So in your program, you might

want to refer to a specific one of many text box tags. Thus, each one needs an individual identifier. In

this example, we only have one text box tag, but it still gets an identifier. The identifier for this text box

tag isTextBox1 (notice the number 1). The Web server recognizes this is an identifier because of the

word IDfollowed by an equals sign and then the identifier in double quotes.

Next comes a rather odd thing called the runat property. Every ASP.NET tag gets one of these. It means

that the tag will be processed by the server, not by the browser. It's kind of silly, though, because all

ASP.NET tags are required to be processed by the server. So having this runat thing is actually a bit

redundant. However, ASP.NET requires we have it, and VWD put it in automatically for us, so there it is.

After the opening <asp:TextBox> tag comes the closing tag, </asp:TextBox>. In this type of HTML, which

is based on a standard called XML (which stands for Extensible Markup Language), every opening tag

must have a closing tag. However, if there's nothing between the tags (as is the case between our

opening and closing asp:TextBox tags), then you're allowed to do a shortcut like this:

<asp:TextBox ID="TextBox1" runat="server" />

VWD didn't use the shortcut when it created the tag, but you're allowed to. However, if you look ahead

to the next tag, you'll see that VWD did use the shortcut in it. It's hard to say what was going through its

mind, but I bet it did this because you can optionally put stuff between text box opening and closing tags

but not between opening and closing tags for a button.

The next tag, as I just mentioned, is the asp:Button tag. It tells the server to create a button. Buttons

usually have some words on them. Inside this asp:Button tag you can see the word Text, followed by an

equals sign. The text that follows, inside double quotes, is the text that appears on the button. As you

can see, the word says Okay, which is what you typed earlier. And if you recall, the property you

changed earlier in the button's Property window was, indeed, Text—the same as the name Text that you

see here in the code.

Page 11: 202

Before making some modifications to this code, let's think a moment about how this code got here.

When you created the new file, VWD created a file that looks like this:

Print code

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

</div>

</form>

</body>

</html>

Page 12: 202

This all provides the basics for a Web page. Don't worry yet about exactly what the different items all

mean—we'll get to that later.

After VWD created this code, you switched to the design mode, where you added some text, a text box,

and a button. When you were making the changes through the designer, VWD was modifying the code

behind the scenes. When you typed text into the designer, VWD added that text to the code. When you

pressed the ENTER key, VWD added a <br /> tag to it. When you dropped the controls on the form, VWD

added the appropriate tags for those controls. Finally, when you modified the text property of the

button, VWD made the changes in the code.

When you work in the designer, VWD makes changes to your code for you. You can go the other way,

too. If you make changes to the code and then switch back to Design view, you'll see the changes. The

only thing you have to watch for, however, is that you don't type something the designer doesn't

understand. For example, if you accidentally type some of the tag names wrong or forget some closing

tags, you'll end up with a mess, and VWD won't be able to switch to Design view. So be careful when

working in Source view.

Adding Code That Responds to Actions

Now we'll make some changes to the code. This will demonstrate the fundamental steps that take place

with a Web page in ASP.NET. I chose these changes carefully for that purpose. So first I'll explain the

steps a bit, and then you'll make the changes to the code and try them out.

When you open a page in a browser, you start by either typing in an address that starts with http://, or

you choose a bookmark or favorite, or you click a link. All of these ultimately cause the same thing to

happen: The browser has an address to go to. It makes a connection over the Internet to the Web server

for that address and requests the page.

In the case of ASP.NET, the page gets created and then sent back down to the browser in the form of

HTML. This was what took place with the sample ASP.NET page you just created in the last chapter. Now

what happens when you see the page in the browser and you click the button?

Well, the browser sends another request to the same Web server requesting the same page. (This isn't

true in all cases, but it is true in the samples in this lesson.) Then ASP.NET runs the code in your page a

second time. Knowing that, let's add some code to the page to demonstrate how we can use that to our

advantage. Here's the code with the changes (I'll talk you through each change to help make sure you

get them right):

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Page 13: 202

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<% If Not IsPostBack Then%>

Hello and welcome to my web site! What is your name?<br />

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:Button ID="Button1" runat="server" Text="Okay" />

<% Else%>

Welcome, <%=TextBox1.Text%>, I'm glad to see you!

<% End If%>

</div>

</form>

Page 14: 202

</body>

</html>

First, make sure you're in the Source view. (If you're not, click the Source button in the lower left.) Then,

position the blinking cursor right after the <div> tag, after the > character. Press ENTER to start a new

line. Then type:

<% If Not IsPostBack Then%>

(You can indent this a bit if you like as shown in the full code. Indentation doesn't really matter though,

and VWD will do its best to indent for you anyway.)

The first character is a less than symbol, followed by a percent symbol. (Don't put any spaces between

these two characters.) Next comes some real, live VB.NET code. The idea here is that the computer will

test whether a certain situation applies. It's looking for whether this page is being viewed for the first

time or in response to a button click on the page. Remember what I said earlier about the order of what

takes place. If the page is already in the browser and you click the button, the browser sends a request

for the same page back to the server. That's what happens here if the page is being requested in

response to a button click.

This situation is called a postback. When the page originally displays, it is not in postback. If the page is

running in response to a button click on the page itself, then the page is in postback.

So in the code, we're testing to make sure we're not in postback—whether the page is being run directly

and not in response to a button click. Look at the code again. It says:

If Not IsPostBack Then

The word If means I'm testing for a condition. The two words Not IsPostBack mean the condition we're

looking for is when we're not in postback. The computer will then run the code following the word Then.

What follows the word Then? The text you originally created and the text box and button. Cool!

Everything I've just said can be boiled down to this: The computer will only create the text, text box, and

button if the page is initially displaying but not in response to a button click.

Now position the blinking cursor immediately before the closing <div> tag (which comes after the

button tag). Press ENTER a couple of times to move that </div> tag down a few lines. Then go back up

and type in the following:

<% Else%>

Before continuing, let's talk about what that means. The lines for the text, the text box, and the button

happen if the page is not in postback. Now, the word Else means that what follows is for the other

situation, in this case, when the page is in postback. Let's continue. Press ENTER once or twice (I usually

do twice for extra spacing, but it doesn't matter). Then type:

Page 15: 202

Welcome, <%=TextBox1.Text%>, I'm glad to see you!

Be careful here. This line doesn't start with the <% thing! I'll explain why in a moment. There are <% and

>% things, however, in the middle. Notice what they go around: =TextBox1.Text. What is TextBox1?

That's the identifier for the text box you created. The .Text part refers to the text that was entered into

the text box.

Remember, the part that we're in right now is the code that runs on the postback. That means the page

already displayed earlier with a text box and a button. The person seeing the Web page was asked the

question, "What is your name?" (Remember, that's part of the text you typed.) When the user types

something into the text box and clicks the button, the page comes back on PostBack, and TextBox1.Text

refers to whatever he or she typed into the page!

What I'm about to say now is extremely important. Understand it and you'll be well on your way to

understanding how Web servers work. So please go over it a couple of times if necessary until it makes

sense.

When you have <% and %> characters inside an ASP.NET page, the ASP.NET system will take the code

that's in between those characters, run it, and finally (here's the important part), replace the code with

the results of the code. Now let me say it again another way that will make more sense. Look at this

code:

<%=TextBox1.Text%>

This is from what you just typed. The thing TextBox1.Text is called an expression, and it refers to

something. It refers to the text that the user typed into the text box the first time the page displayed. If

the user typed George Washington, then this TextBox1.Text would refer to the words George

Washington.

When ASP.NET takes your page (which I'll call an aspx page), runs the code, and builds an HTML file, the

HTML file will be identical to the aspx page, with one notable exception: All the ASP.NET code will be

replaced by HTML code. That means the code inside <% and %> tags will be replaced with HTML code,

and all the tags that start with asp (such as <asp:TextBox>) will be replaced with HTML code. Sometimes

the HTML code will be nothing but a space or nothing at all, but nevertheless, all the ASP.NET code will

be gone, and HTML code will likely be in its place.

So look once again at this:

<%=TextBox1.Text%>

This is ASP.NET code. It will be replaced by something. In particular, it will be replaced by what the

TextBox1.Text refers to, which is whatever the users type. If they typed George Washington, then the

code will be replaced by the words George Washington.

To make a long story short, then:

Page 16: 202

When you have this in your aspx file:

<%=TextBox1.Text%>

The final HTML file will replace it with whatever TextBox1.Text refers to, which is what the user typed.

And shortly you'll see this in action! Let's resume. There's one more line to type. Add another blank line,

and then type:

<% End If%>

Your code should now look like the complete code sample we looked at earlier. You should have four <%

%> tags. The first one has an If statement. The second one has an Else statement. The third one has an

equals sign and the Text property of TextBox1. The fourth one is an End If statement, which closes out

the test for whether this is a postback or not.

Now run the code by pressing CTRL + F5. Your page should open in the browser. If it doesn't, and you

instead get a message box that says, "There were build errors," then here's what you do.

Click No, meaning you don't want to run it. Then you'll see a list of errors pop up at the bottom of the

screen. In general, you can ignore the ones that say "Validation Error." Then simply double-click the

error messages in the error list, and you'll be taken to the place in your code where you typed

something wrong. See if you can figure out what's wrong. If not, look closely at your code and the code

I'm showing you here until you find the mistake. Go ahead and fix it, and then try pressing F5 again. (And

remember, even the best programmers see many errors on a daily basis. Nobody's perfect, so don't

worry!)

When the form opens in your browser, you should see the question and text box. Type something into

the text box (don't leave it blank!) and click the button. You'll see the browser wait for a split second or

more, and then you'll see the page open saying, "Hello, Jeff, I'm glad to see you!" (or whatever name

you typed in).

That's it! In the next chapter, we'll talk more about the process that just took place to make sure you

fully understand it.

Understanding the Callback Mechanism

In the previous chapter, you put together a single aspx page that serves two purposes. First, it presents a

page to the user asking for a name. Second, when the user enters a name, it prints a message displaying

it.

Now think about that for a moment. You created a single aspx page, but it results in different

information displaying in the browser, depending on the situation. That's the general story with dynamic

Web pages. Although I'll continue calling what you created an aspx page (and I just pronounce the

individual letters A-S-P-X), you didn't actually create a single Web page. Instead, you wrote a Web server

Page 17: 202

program. The program did some processing and created a page to send back to the browser based on

what it determined in its processing.

In general, with ASP.NET programming, your programs will follow the pattern outlined in the program

you just wrote. You'll build an aspx page where users can interact with your Web site, and the page

HTML generated by your program will vary depending on how your program processes the current

situation.

Running the Program Again

Go ahead and rerun your program. Note, however, that pressing CTRL + F5 isn't necessarily the way you

always want to run your program. Here's why. Let's say you have several aspx files in your program. If

you press CTRL + F5, one of two things will happen: If you've set up your project to always run a

particular page, that page will run whether you're looking at it in the editor or not. Or, if you haven't set

up a particular page to run, whatever page you're currently looking at will run.

In my Web sites, I usually have a particular page set up to run that will be the main page. This page runs

if I just press CTRL + F5. But I'm usually working on several pages. So if there's some other page open in

my editor and I want to run it, here's what I do: I right-click inside the editor, and in the pop-up menu

that appears, I choose View in Browser.

The View in Browser pop-up menu item

Go ahead, then, and rerun your program using this method. Make sure your myname.aspx file is open in

the editor. Right-click in the editor, and choose View in Browser.

Looking at the Resulting HTML

Page 18: 202

With your main page visible in the browser (the page asking for your name), take a look at the source

code. If you're using Internet Explorer, the easiest way is to right-click in the browser (not in VWD!) and

click View Source. If you're using Firefox, right-click in the browser and choose View Page Source.

You'll then see the HTML source in a text editor. You don't have to worry too much about the detail. I

just want you to notice the similarities and differences with the aspx file you created in VWD. In general,

the page is very much like the aspx file, except there are some extra codes added that ASP.NET uses.

And the text box and button controls got replaced by actual HTML code consisting of the <input> tag.

(Again, you don't have to worry about the details. That's one reason you're using ASP.NET—so you can

stay away from the annoying details!)

Now close the text editor showing you the HTML source, and think about the situation so far. Your

browser is simply displaying an HTML page, that's all. The page has some text in it and some controls.

Now go ahead and enter a name, and then press OK.

As before, the page comes back with the friendly message, and the text box and button are gone. Again,

look at the source code. Again, the ASP.NET code is gone and has been replaced by text. And, once

again, the page consists just of plain old HTML.

The truth is, your browser knows nothing whatsoever about ASP.NET. Remember, ASP.NET runs on the

server side. The browser doesn't know any ASP.NET, and your browser doesn't have to know any

ASP.NET. Your ASP.NET program carefully created an HTML page and sent it down to the browser, which

dutifully displayed the page.

Here's another way to look at how your program ran. You can think of it as running twice. The first time,

your program generated HTML for a text box and a button. The user of the browser clicked the button

and then, back on the server, your program ran a second time. This second time your program detected

that it was in postback mode and generated some different HTML.

So you can think of your program as having run twice. Actually, that's an important fact that will come

up again and again throughout your ASP.NET programming. Understanding it will help you program

more successfully. So remember that your aspx page ran twice on the server. It might seem a little odd

to look at it this way, but it really is what happened.

Conclusion

In this lesson, you created a real, live server-side Web application. If this was your first time with Web

programming, congratulations! Although dropping the text box and button on the form and typing code

was fun, the important part that I want you to get out of today's lesson is the chain of events that

occurred. First, your program ran and created an HTML page that was sent down to the browser. That

HTML page allowed the user to enter some information, which got sent back to your program. Then,

your program ran again, this time using the information the user entered to create a new set of HTML

for the browser to display.

Page 19: 202

This basic idea is the fundamental machinery behind most of the more powerful Web sites. Different

sites use different languages and servers (you're using ASP.NET with VB.NET or C#), but the whole idea is

fundamentally the same: Your server program creates an HTML page that lets the user interact with

your program. When the user enters information, it gets sent back to your program. Your program can

then further process the information, likely creating a new Web page in response to it.

That's it for today. Next time, we'll explore the process a bit further, going into more detail about what

goes on behind the scenes when you create a Web page. And while we're at it, we'll try out all sorts of

goodies, including a list box control. See you then!