http://www.developer.com/

Back to article

VB.NET Uncovered: Working the Web


October 21, 2002

Welcome to the third part of the VB.NET Uncovered series, Working the Web.

If you haven't yet checked out Getting Started or Big Changes, be sure to review them before reading on.

Today, we're going to be taking a sneak geek peek at Working the Web in VB.NET.

Now, with Visual Basic 6, we saw a fair bit of Internet functionality sneaking onto the scene. WebClasses, the WebBrowser, that Winsock control. But that was where it stopped - nothing particularly exciting - and WebClasses seemed more of an afterthought than a usable technology.

But in VB.NET, the Net plays a very key role.

First off, you have something called Web Services, effectively the DCOM replacement that we'll be looking at next week.

Secondly, and the main subject of today's tutorials, we have Web Forms. And this Web Forms concept allows you to effectively build fully interactive Web sites without any of the old ASP or CGI rubbish. You could even do it without knowing anything about HTML (though for aesthetic purposes, I plead you don't).

So, without any further ado, let's move on to find out how we can Work the Web in VB.NET...

Before we dive into the nuts and bolts of Web Forms, let's fill up the ol' pipe and sit around talking theory for a mo.

Now, what's so wrong with the Web development tools we have right now?

Well, for any serious development, you're really going to have to head for ASP. And I have to admit - I just don't like it.

For a start, the code can get messy. You're mixing the presentation layer (the actual HTML) with your ASP code. It's like putting all your code behind forms. Sure, there are ways to get around it - but it's still messy.

Next up, you have to mess around supporting all those users with old computers that never bother to upgrade their Web browser (damn them). If their browser doesn't, say, support JavaScript, you need to detect that and change your page to suit.

There's state management too. Someone logs in and you want to remember his or her preferences - so you try twiddling with the Session object. And then your site grows and you own a Web Farm - suddenly, multiple machines need access to the Session object. And you get stressed. And it gets messy.

Quite miraculously, VB.NET solves all of these problems with Web Forms.

Now, Web Forms are a part of the newly-rechristened ASP.NET (no longer ASP+). They're effectively interactive Web pages you create inside VB.NET. And it's all very easy.

You simply create a "Web Form" in VB.NET. This process is similar to designing a WebClass - and unfortunately, the interface is just about as advanced which means you're probably better off designing a fancy page in FrontPage, then pasting the HTML over to your VB.NET Web Form.

Top Tip: In that last paragraph, I said you could write code in FrontPage, then paste it over to your VB.NET Web Form. Slight lie, that. When I tried, it seemed to accept very simple pages - but as soon as the form layout got a little complex, it bunked. This should fix itself in later versions.

So, you've designed your skeletal page, the Web Form. You can then add the interactive elements in VB.NET - such as a regular text box or submit button. You can also add 'Web Controls', which are more advanced HTML features that aren't like ActiveX controls and don't require a separate download. They also work with any browser - we'll be looking at this in more detail later today.

Top Tip: VB.NET bundles with a bunch of Web Controls - the Calendar control being the most impressive. We'll meet this one later today.

After designing the page and adding the elements, you tap out a little code to make it all work together. So, let's say you have a text box and a button on your Web Form. You might add code behind the button to take the value behind your text box and display it in a label. Or add it to a database. Or verify it against a list of users, then redirect him/her to the members area. Or whatever.

The core message here however is that you can treat the entire page and objects on it as objects. You're not thinking about 'requesting' certain form fields, as you would in the old ASP world. Here, you just refer to the objects as you would a regular Windows Form - and you've done it!

As we're comparing the old ASP to the groovier ASP.NET, let's review the problems I mentioned above and see how they're solved.

First off, the HTML getting mixed with ASP code. You don't have that in VB.NET - the HTML page is completely separate from the code. There's only one line right at the top of your Web Form that refers to the code module. The Web server does the rest.

Top Tip: Just as old ASP files had a .ASP extension, Web Forms have a .ASPX extension. When the Web Server serves up this file, it is processed by the .NET Framework first - and 'Web Controls' are converted into HTML, your code is compiled and so on - all automatically for you. We'll look at this more later.

Next up, with the old ASP, you'd mess around checking the users browser and altering the content you send depending upon its capabilities. With VB.NET, it's all handled for you - the .NET Framework only spews out HTML that can be understood by the target browser. No problemo.

And what about state management? Ohh, this is a touchy subject for most ASP programmers. Bane of their lives, they'll tell you. Well, in ASP.NET, state is encoded and stored in the page sent back to the user (it's essentially a hidden field). The next time that page is submitted, the data can be read and used as and when.

Top Tip: You can think of state management in ASP.NET as similar to using Property Bags. It will automatically add certain things to the Property Bag - such as text box values - plus you can add bits yourself, then refer back to them later. If you want to get all technical, you'd say that the state information is "tokenized"

Another Top Tip: Tests have shown there to be a performance advantage in using this method of state management over the old ASP Session object.

Yet Another Top Tip: Security is still an issue here - the data is apparently encoded to a high standard, however if you need real security during a particular operation, you may need to use this state management alongside existing database passwords records and all that jazz. Depends on what you're looking for.

Well, that's ASP.NET for you. It's new, it's groovy, it's what the ASP world has been begging for. And if you're a Visual Basic programmer looking to get your foot in the Web world, this is the ideal opportunity.

So... as some singing chick once said, let's get physical.

Wanna see something really scary?

Well, you might want to check out part six, our VB.NET object oriented programming instalment. Or a Twilight Zone flick. Or my hair at six in the morning.

But not this section - oh no - this ASP.NET thing is quite literally a doddle. And just to prove it, let's throw away the boring theory and jump straight in with a little practical:

  • Launch VB.NET
  • Create a new Web Application

Note that the location is no longer a file path - it's a HTTP address, probably that of your local IIS-running machine. In the instance above, I've created GroovyWeb on http://ABYDOS - which means my final project will be available at http://ABYDOS/GroovyWeb/

After a little whizzing and whirring, WebForm1.aspx should appear and your screen should look a little like this:

Now, we're going to create an application that accepts a name in a text box and places it in a label on the form. Simple, yes - and not exactly something that'll win you Innovator of the Year award - but it'll demonstrate a whole bunch of new concepts.

  • Drag-and-drop a Label, TextBox and Button onto your Web Form - in that order - separate them onto individual lines if possible

Top Tip: Note that in the designer, you can't 'draw out' controls as you can with Win Forms. Tsk, sacrifices, eh? Nevertheless, you still get access to the related properties via the Properties window - allowing you to change names, style, etc

Your form right now should look a little like this:

Before we add a little code, let's browse through the HTML that makes up the page we've just created:

  • Change the Web Form mode from Design to HTML, by clicking the appropriate button at the bottom of your form

Now this is interesting. First off, look at that first, yellow-highlighted line. Among other things, this tells your .ASPX page where its code lies - as you can see, Codebehind="WebForm1.vb" - we'll stumble across this file in a few minutes.

Now, controls such as the labels and text boxes, which we'd usually define with regular HTML tags - here have the <asp:...> </asp:...> tags. This is so they're identifiable as ASP.NET "controls" that can accessed in code, etc.

Top Tip: Even though they may have tags here, the controls are converted to regular HTML before sent to the browser. No fear.

Much of the code here however looks like regular HTML. And if you're used to that sort of thing, you should have no problem understanding it.

  • Switch back to Design mode

Right, enough messing around. Time to add a little code:

  • Double-click your Button

You'll be shown the Web Form code window. Whoops, once again a bunch of pre-written code just to confuse you. Some of it is quite useful - such as the code behind the Load event, which includes sample code to detect whether the page has already been loaded or this is a 'post back'.

Top Tip: Notice that the code window is called WebForm1.vb? Ring a bell? Please, please, tell me it does...

Have a play around.

Erm, later. For now:

  • Type in the following code:
Label1.Text = TextBox1.Text

When I first tried this out, it all felt pretty eerie. This is just the sort of code you'd expect to write in a regular Visual Basic application - however having worked with ASP and CGI and the like, I know doing it on the Web is soooo much more difficult.

Well, let me surprise you.

  • Hit F5 to 'run' your new Web page

Top Tip: When I hit F5, I get an annoying message about my security permissions being set incorrectly. It's wrong, coz they're set all proper like. If you have the same issue, simply hit OK, load Internet Explorer and access the page manually - for example, my page has the address: http://ABYDOS/GroovyWeb/WebForm1.aspx

Now, it may initially take a good few seconds for your page to load. That's because the Web server needs to compile your code - it does this automatically the first time your page is accessed. Any later changes mean another recompile - however once again, this is all automatically done on 'first access'.

  • Enter your favourite colour on the Web Form, then click that button:

Almost immediately, your form should post the data and come back with something like this:

Hurrah! Look at that! In just one line of code, you've created something that would take a regular ASP programmer a good while longer to create.

Top Tip: Try viewing the page source at this point (click View, Source). Wow, that's all been automatically generated for you! Note the hidden field, __VIEWSTATE - that's the encoded data I was referring to earlier. Right now, it contains information such as values of the controls and such. As you perform more complex operations, you'll notice it grows and grows in size - however performance is still apparently better than with previous Session methods

Well, that's our Hello World finished with. Next, let's move onto something a little more complicated - a brief look at Web Controls, plus a few of the Web Form events.

Next up, we're going to create a Web page that allows the user to book an appointment with their doctor.

They simply type in their name and select a date. If they omit their name, we get very angry and display an error message.

So, let's add a new Web Form:

  • Add a new Web Form (Project, Add Web Form - keep the default name of WebForm2.aspx)

Next, we're going to modify our existing page so it links to the new one:

  • Navigate back to WebForm1.aspx
  • Add a CheckBox to the Web Form
  • Change its Text property to: Move baby move!

By default, when you click the CheckBox, the page isn't sent back to the server to be processed. But to prove it can be done (and cunningly demonstrate another concept), let's override this default behaviour:

  • Change the AutoPostBack property to: True

Now let's add a little code to redirect the page when this CheckBox is clicked:

  • Double-click on the CheckBox on WebForm1.aspx
  • Enter the following code:
Navigate("WebForm2.aspx")

Top Tip: Instead of using the new Navigate keyword, I could have simply done a Response.Redirect("WebForm2.aspx") - similar to the old ASP format. That's because the Response, Request, Server, Session and Application objects are all still available to you. Have a play around - plus, if you have time, you might want to check out the ClientTarget, ErrorPage, IsValid, User and Validators keywords.

That's the redirection sorted. Now let's move on to designing WebForm2.aspx:

  • Navigate to WebForm2.aspx
  • In the Form window, type in: Name -
  • Drag-and-drop a TextBox control after your 'Name' text
  • On the next line, type in: Pick a date -
  • Drag-and-drop the Calendar control on the next line
  • Below all of this, add a Button control
  • Change the Button Text property to: Make Appointment

Next, we're going to add a control that will check whether our TextBox contains a name. If it doesn't, this control becomes visible and 'raises an error'. Here goes:

  • Finally, add a RequiredFieldValidator control to the bottom of the Form
  • Change the Validator ErrorMessage property to: Oi, u forget ur name!
  • Change the Validator ControlToValidate property to: TextBox1

Your Form should look a little like this right now:

Now, let's add just a little code behind the 'Make Appointment' button:

  • Add this code behind your Button:
Button1.Text = "Appointment for " & TextBox1.Text & " booked on " & Calendar1.SelectedDate

And that's it! Here, we've built an application that requires the user to input their name (if not, an error appears) plus select a date. And when they click the 'Make Appointment', its Text property verifies the details you've entered.

Top Tip: You can actually check whether control validation has succeeded in your code by using the IsValid property. Check out the help for more information.

  • Press F5 to test your page

So, check out your new work! First off, check the box on WebForm1.aspx - then, on WebForm2.aspx, try clicking the button without entering a name. Next, enter a name and select a date - notice how the Calendar Web Control automatically highlights everything for you. Finally, click the Button and stand in awe of your accomplishments!

Top Tip: If the CheckBox doesn't redirect you, there could be a problem with WebForm2.aspx. When I visited my page directly, I received an "Invalid Base Class" error message. I found the solution was to 'compile' my page inside of VB.NET - by opening WebForm2.aspx and select Build, Build from the menus. This seems to be a common problem and should be fixed by Beta Two.

Of course, we could be doing anything behind that Button. Adding the users details to a database, retrieving information based on their input, verifying their details and 'logging them in'. Anything!

Ahhh, the power!! <evilLaugh> Hahahaha... muhahahah! </evilLaugh>

Ahem. Oh boy.

Well, that's about all for this instalment of VB.NET Uncovered.

Today, we've explored Web Forms. We started off by looking at how it all works in theory, then went on to create our own interactive pages with Web Controls - similar to something that would take days in modern day ASP.

Keep playing around with Web Forms - and try looking up the 'Web Forms Introduction' in the help for more information and sample code - to keep you well ahead of the rest.

Next week, we'll be exploring Web Services, the VB.NET DCOM-replacement sure to knock your cotton socks off.

But until then, this is Karl Moore signing off, wishing you all a very pleasant evening, wherever you are. Goodnight!

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date