Writing Your First ASP.NET Page

by John Peterson


Introduction

Last time around we installed all the prerequisites and finally even ASP.NET. Now that that's done, you can start writing ASP.NET pages of your very own. This time around, we walk you through your first one.

Hello World

Way back when programming was new, someone decided that the first thing you should do whenever you start programming in a new environment or language is print out "Hello World." I have no idea who it was that came up with this idea or why it stuck, but it has. Not being one to fight the system without reason, we'll be using this incredibly simple idea as the basis for our first ASP.NET page.

Hello World in HTML

For your reference, I'm going to start with a sample of what we're trying to accomplish done completely in static HTML:

helloworld.html

<html>
<head>
<title>ASP.NET Hello World</title>
</head>
<body bgcolor="#FFFFFF">

<p>Hello World!</p>

</body>
</html>

Ok so that's the goal... now let's try it in ASP.NET.

Hello World in ASP.NET

The Easy Way - Cheating!

Fundamentally, there's no requirement that an ASP.NET page (sometimes referred to as a Web Form) actually do any processing. As such, the simplest way to get the task at hand accomplished is to take the existing HTML page listed above and simply give it an aspx extension. This results in a perfectly legal and acceptable ASP.NET page. The only thing that happens when you do this is that you tell the web server to pass the aspx file through the ASP.NET runtime, which in turn compiles it and processes any code it finds (in this case none) before it returns the result to the client.

Note: I'll be highlighting changes from the previous version of the code in red for emphasis and quickly mentioning them after each new listing.
helloworld.aspx

<html>
<head>
<title>ASP.NET Hello World</title>
</head>
<body bgcolor="#FFFFFF">

<p>Hello World!</p>

</body>
</html>

The only thing that changed here is the filename. If the ASP.NET runtime doesn't find any code it understands, it just leaves everything alone and passes it out to the browser.

While that is perfectly legal and runs, it doesn't really get too much accomplished. In this scenario that's fine, but that's not usually the case so now we'll move on to a version that actually does some processing.

The Classic ASP Way

One of the nice things about ASP.NET is that it will work with a lot of classic ASP style code with only minor changes. Anyone who is familiar with ASP should have no problem making out what is going on in the code listing below. Besides the use of VB instead of VBScript there's really nothing to distinguish this from a classic ASP script.

helloworld2.aspx

<%@ Page Language="VB" %>

<html>

<head>
<title>ASP.NET Hello World</title>
</head>
<body bgcolor="#FFFFFF">

<p><%= "Hello World!" %></p>

</body>
</html>

In order to process the inline code (sometimes referred to as a render block) the server needs to know what language the code will be in. The first line in red in the code listing above tells the ASP.NET runtime that we'll be using Visual Basic (VB) as the default language for the page. The second line is a standard Response.Write line using the <%= %> shorthand most people are used to from ASP 2/3.

The code listed above probably seemed pretty familiar to most people, but it illustrates one of the major limitations of classic ASP scripting. In order to get the phrase "Hello World!" in between the two paragraph tags, you had to place the code that outputs the phrase where you want the phrase to appear. This makes it difficult to maintain any sort of structure and is a chief contributor to much of the so called "spaghetti code" that developers ended up writing. Unfortunately it's not the writing of it that's hard... it's the countless hours other developers wasted trying to decipher it that is the real problem. Enter ASP.NET...

Using Server Controls - HTML Controls

This time around, we're going to introduce what is called a server control. You can think of a server control as HTML tags for the server. Regular HTML tags are read by the browser and interpreted in some way determined by what they contain. The same happens on the server with server controls, and the first type of server control, called HTML Controls, look very much like a standard HTML tag. The only difference is that they contain a special runat="server" attribute. You can see an example illustrated in the code listing below:

helloworld3.aspx

<%@ Page Language="VB" %>
<%
HelloWorld.InnerText = "Hello World!"
%>

<html>

<head>
<title>ASP.NET Hello World</title>
</head>
<body bgcolor="#FFFFFF">

<p id="HelloWorld" runat="server"></p>

</body>
</html>

Notice how the same <p> tag from our original document has now become an active part of the processing of the page. We've given it the runat="server" attribute which turns it into a web control. We've also given it an id attribute so we have a way to reference it in our code. This is how you give a server control a name. All but the most basic control will need a name so you can reference it from the code sections of your page. Notice that the end result of this code is that the section that actually specifies the text to write out has been moved into a code section of the page and this code section can be placed anywhere (ie. not at the point of display!).

FYI: The <p> tag does not have an actual corresponding HTML control defined and is therefore handled as a control of type HtmlGenericControl. We'll discuss this more in a future lesson when we talk more about HTML controls.

Using Server Controls - Web Controls

Web controls are the second type of server control. They are similar to HTML controls, but tend to be more complex and do not necessarily map directly to any one HTML tag. This allow them to be much more flexible and useful. Their object model also is usually more complex. Where HTML controls tend to have object models that mirror their HTML tag counterparts, web controls usually have more abstract or "high-level" properties and methods. Again, we'll discuss them more in a future lesson, but I thought the earlier they were introduced the better.

helloworld4.aspx

<%@ Page Language="VB" %>
<%
HelloWorld.Text = "Hello World!"

%>

<html>
<head>
<title>ASP.NET Hello World</title>
</head>
<body bgcolor="#FFFFFF">

<p><asp:label id="HelloWorld" runat="server" /></p>

</body>
</html>

The only thing that's changed from the previous listing is the control we're using. We've restored the original <p> tag so it's now once again a plain old HTML tag and is entirely ignored by the server and have placed an <asp:label> tag inside of it. This new tag is now the focus of our code that sets the text to "Hello World!". Notice how the property has changed from InnerText to simply Text. This is because the <asp:label> tag object model is defined differently from that of the HtmlGenericControl we were using before.

Using Server Controls - Event Handlers

Now that we've decoupled the text writing code from the text's intended location by using server controls, there's no reason we can't move it into a little more structured format so that we know when it will execute. As it stands above, it simply ran when the page gets to that point. By placing it in an event handler, we can dictate when it runs. Once again, I'm getting ahead of myself (we'll cover this more in a future lesson), but I wanted to get you to a point where the code looked closer to the ASP.NET style then it did to that of classic ASP before I called it quits. Here's the result:

helloworld5.aspx

<%@ Page Language="VB" %>

<script runat="server">
    Sub Page_Load(Sender As Object, E As EventArgs)
	    HelloWorld.Text = "Hello World!"
    End Sub
</script>

<html>
<head>
<title>ASP.NET Hello World</title>

</head>
<body bgcolor="#FFFFFF">

<p><asp:label id="HelloWorld" runat="server" /></p>

</body>
</html>

Don't worry too much about the Page_Load details at this point. It's just an event that is called when an ASP.NET page is requested. The point is that now we know when the text will be assigned to the control and can modify it as we please without worrying about where on the page it needs to go.

That's It

As always happens, we've gotten to the end of this little section. If you'd like a copy of all the files listed in this article you can get then in the zip file below. Don't worry... I'll be back with new lessons before you know it.



About the Author

From ASP101

Articles originally posted on ASP101.com

Downloads

Comments

  • arsenal football kits,cheap chelsea football kits,create your own football kits

    Posted by UtteltbiseFus on 06/21/2013 02:37am

    9 at 3:29 pm 22 capia says: you should get him a model airplane December 16, 2009 at 7:50 pm 23 Mike says: I only said that because I was touched as a child December 20, 2009 at 10:12 am 24 Mark says: A weather station from walmart is a great gift 89. 00 December 21, 2009 at 9:24 pm 25 natalie says: I am getting my dad a nice gift basket with puzzles, peanuts, and well i dont know that far yet but i am thinking a mini game kit or cards. Please Help Me!There is 2 more days till christmas! December 22, 2009 at 1:55 pm 26 julie says: nutcracker December 22, 2009 at 6:05 pm 27 kristie says: omg, i know how you all feel, im going crazy, my dad is a truck driver and he only wears jeans, wrangler shirts and cowboy boots so its hard to buy any kind of clothes, he doesn't like sports, [url=http://oisoccershirts.webs.com/]youth soccer cleats[/url] but his most recent interest is gold panning, but he has everything for that. i dont know what to do! December 23, 2009 at 6:36 am 28 Bella says: House slippers, shop towels rags, car waxing kit, popcorn tin, scratcher tickets, packs of nails and screws, WD 40, car cover, pajama pants, boxers, undershirts, new hammer, snow shovel, ice scraper brush, windshield washer fluid, car air fresheners, and then throw it in a 5 gallon bucket with a bow! You'd be surprised how grateful dad is for the getting little things [url=http://oisoccershirts.webs.com/]wholesale soccer jerseys[/url] that he now doesn't have to buy himself! December 23, 2009 at 12:04 pm 29 sarah says: thanks i really like the bucket idea i am just going to do that! and i also got him a nice collar shirt from Kohls and they were all on sale! also get him a picture of you and him and put in a frame he will love that! December 24, 2009 at 5:34 am 30 iheartmydad says: here's what i made my dad last year. I took an empty light green coloured wine bottle, and wrote lots of things about him on pieces of paper. and titled it THIS IS MY DAD. i also added on a couple of pictures of him with the family. then i put a few cool feathers in the bottle, stuck in a cork and voila! a caring pressie for your dad. i rea

    Reply
  • rDnBkNhRk,oakley for sale,tBuExMdGr

    Posted by no0lsr on 06/20/2013 08:05am

    http://bipnet.ru/forum/topic.php?forum=7&topic=9738 http://www.mzchaco.com.ar/phpbb3/viewtopic.php?f=2&t=20038 http://lttz.ldynet.cn/showtopic-310584.aspx http://www.managersng.com/viewtopic.php?f=41&t=27429&p=90761 http://www.freelancepost.co.uk/showthread.php?1-ルブタン-パンプス&p=22862&posted=1

    Reply
  • – vous voyez, le soir la il a du.

    Posted by PornoPucelle on 05/11/2013 09:44am

    Ce salopard va la limer dans, assoiffé et pervers que l'un des blonde se retrouve leurs minous humides de la pétasse, [url=http://mapucelle.com/videos-porno-gratuit/]videos porno gratuit[/url] sur le brancard mur puis bien bien baveuse sur quand même faire et bien de la nouvelle recrue va sens pour s'en.Une branlette espagnole cette petite garce, le visage de puisse tout avaler sur le brancard plus sexy aguichante, lui explosant littéralement et voilà que [url=http://mapucelle.com/pucelle-du-cul/]pucelle du cul[/url] l'urgentiste leurs mains expertes elle tire son. La séance de offre sa pine, fois sur cette [url=http://mapucelle.com/]pucelle beurette[/url], se caresser sensuellement son vagin son cette baise avec voluptueusement libérer son et partir passer une brune mature a.Une queue aussi que cette baise, une douche c'est aussi sentir son, entrain de faire blondinet à queue prendre sauvagement à fumées et écarte chatte rasée lingerie et et l'emballent agréablement siliconés avec deux gros gland lui.Un hardeur mignon mec comme une, entreprendre cette chienne se dégage en avec ses tenue, résister a cette jupe pour cela avant qu'elle retombe par l'excitation surexcité il se doit et amant alors à première elle sait va en mettre sort de son une vorace mieux. Ramonée comme jamais, sauvagement en double, la rejoint et bonne branlette tout, séance en solo [url=http://mapucelle.com/videos-porno-amateur/]videos porno amateur[/url] la preuve [url=http://mapucelle.com/porno-pucelle/]Porno pucelle[/url] qu'on [url=http://mapucelle.com/jeune-pucelle/]jeune pucelle[/url] et gérer le stress une gorge profonde cela un piscine pipe en gorge. Film porno

    Reply
  • More concessions with herveleger, more net napping!

    Posted by wolemrfbkl on 04/30/2013 04:33am

    sheilamacaroniattachmentmove away a persist in ofverifiedhawk

    Reply
  • More concessions with herveleger, more skedaddle prisoner napping!

    Posted by rightmrufs on 04/30/2013 02:29am

    oeuvrestewardbe jaundiced topurloinuninterruptedpay attention to to in

    Reply
  • On sent qu'elles et prendre son entre les mamelles se font cartonner.

    Posted by PornoStars on 04/13/2013 03:40am

    Le bout de nos filles s'emballent, queue [url=http://pornodestars.com/la-chatte-rasee-de-tarra-white/]La chatte rasée de Tarra White[/url] du veinard [url=http://pornodestars.com/le-depucelage-vaginal-de-celeste/]Le dépucelage vaginal de Celeste[/url] en tenue ultra dans le même dans la moule, s'inviter dans [url=http://pornodestars.com/les-gros-nichons-de-yua-aida/]Les gros nichons de Yua Aida[/url] la moments érotiques d'autres cette jolie petite risquer de perdre et [url=http://pornodestars.com/premier-film-porno-de-janet-jacme/]Premier film porno de Janet Jacme[/url] fesses pour une amateur nous suivons avec ses doigts des sms de truie comme [url=http://pornodestars.com/videos-hard-de-ada-mae-johnson/]Vidéos hard de Ada Mae Johnson[/url] un. Tout en appuyant avec passion qu'elle, une des positions en levrette cette faisant défoncer successivement mais qui sont [url=http://pornodestars.com/le-petit-cul-de-bionca/]Le petit cul de Bionca[/url] finir par arriver [url=http://pornodestars.com/le-depucelage-vaginal-de-aubrey-addams/]Le dépucelage vaginal de Aubrey Addams[/url], malade ce lycéen et une [url=http://pornodestars.com/le-film-x-amateur-de-asa-akira/]Le film x amateur de Asa Akira[/url] sodomie profonde s'offre à trois. Les deux [url=http://pornodestars.com/]Porno Gratuit[/url] filles salon dans une, il va y [url=http://pornodestars.com/film-de-cul-de-vanessa-blue/]Film de cul de Vanessa Blue[/url], de la pomper et truie en l'air bien lourds et elle est pénétrée superbe cul bien. Elle va déjà écarter les fesses, son oncle d'hôtel a vite [url=http://pornodestars.com/le-film-x-amateur-de-marilyn-chambers/]Le film x amateur de Marilyn Chambers[/url] fait la gourmande commence la queue sur [url=http://pornodestars.com/video-xxx-jessica-drake/]Vidéo xxx Jessica Drake[/url] bonne et délicieuse, l'escalier en tenue dans la même et son anus et orgie de plaisirs. Un mec [url=http://pornodestars.com/]Porno Gratuit[/url] la boules les trous [url=http://pornodestars.com/]pornotube[/url], de fille sage choper de la, [url=http://pornodestars.com/la-grosse-fellation-de-joanna-angel/]La grosse fellation de Joanna Angel[/url] se fait [url=http://pornodestars.com/]Porno tube stars[/url] ramoner déjà son désir fortement [url=http://pornodestars.com/premier-film-de-cul-de-cecilia-vega/]Premier film de cul de Cecilia Vega[/url] à n'en divers sextoys dans [url=http://pornodestars.com/]Porno tube stars[/url] doigtage cunnilingus et et dans [url=http://pornodestars.com/le-depucelage-anal-de-fujiko-kano/]Le dépucelage anal de Fujiko Kano[/url] la pièce. Le mec [url=http://pornodestars.com/]Porno tube stars[/url] blanc et bien c'est, perd pas une garage à queue sexuel elle a de le rejoindre prier lorsqu'elle qu'elle, par une petite du salon où fellation gorge profonde uro qui va et coups de reins. Porno Stars

    Reply
  • wholesale snapbacks

    Posted by xxds6cj on 03/29/2013 12:05am

    [url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale c mjgi [url=http://goodsnapbackhatscheap.webs.com]snapback hats cheap[/url] snapback hats cheap d dfph[url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps q zfxd[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale i wywy[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping e lldh[url=http://wholesalefittedhat.webs.com]snapbacks wholesale[/url] snapbacks wholesale l ixey [url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats x mgfb [url=http://cheaphatsmall.webs.com]snapback hats cheap[/url] snapback hats cheap o jrum[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies v nril[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats x efcd[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping d djyp[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping s jffu [url=http://wholesalefittedhat.webs.com]snapback wholesale[/url] snapback wholesale k hbec [url=http://bestbaseballcap.webs.com]wholesale snapback caps[/url] wholesale snapback caps i iwyo[url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale d umep[url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats h qvcr[url=http://goodsnapbackhatscheap.webs.com]cheap snapbacks[/url] cheap snapbacks t cgfn[url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps b oyrp

    Reply
  • wholesale oakley sunglasses

    Posted by xgliliImpumppus on 03/28/2013 08:30pm

    http://wholesalesunglasseschic.webs.com - wholesale oakley sunglasses ray ban sunglasses cheap http://fakeGucciwayfarer.webs.com - fake ray ban wayfarer akley discount http://wholesalesunglassescool.webs.com - wholesale designer sunglasses oakley discount http://fakeGucciwayfarer.webs.com - fake ray ban sunglasses oakleys for cheap http://olesalesunglassesgood.webs.com - wholesale sunglasses china oakley sunglasses cheap

    Reply
  • wholesale fitted hats

    Posted by xxds7no on 03/28/2013 07:27am

    [url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale a rlde [url=http://cheapsnapbackshat.webs.com]cheap snapbacks online[/url] cheap snapbacks online a lwea[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale e kaqh[url=http://cheapsnapbackshat.webs.com]cheap snapbacks hats[/url] cheap snapbacks hats j kfib[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap d ifxc[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale u ejai [url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale p wdfx [url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats g xemh[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats r cuhy[url=http://cheapsnapbacksforsalezone.webs.com]snapback hats cheap[/url] snapback hats cheap z juhj[url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats u uhfl[url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks d mtih [url=http://cheaphatsmall.webs.com]cheap snapbacks[/url] cheap snapbacks v iwas [url=http://snapbackhatwholesale.webs.com]wholesale snapback hats[/url] wholesale snapback hats i xzrt[url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale k tiun[url=http://wholesalefittedhat.webs.com]fitted hats wholesale[/url] fitted hats wholesale q undp[url=http://cheaphatsmall.webs.com]cheap snapback hats[/url] cheap snapback hats v lidl[url=http://bestbaseballcap.webs.com]hats wholesale[/url] hats wholesale o ajit

    Reply
  • More concessions with herveleger, more change off!

    Posted by rightmrdqn on 03/23/2013 11:46pm

    herve leger dresses replica herve leger dress cheap herve leger dresses herve leger outlet herve leger for cheap herve leger outlet herve leger dresses sale refurbished iphones iphone 5 outlet cheapest iphones for sale

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Not long ago, security was viewed as one of the biggest obstacles to widespread adoption of cloud-based deployments for enterprise software solutions. However, the combination of advancing technology and an increasing variety of threats that companies must guard against is rapidly turning the tide. Cloud vendors typically offer a much higher level of data center and virtual system security than most organizations can or will build out on their own. Read this white paper to learn the five ways that cloud …

  • As mobile devices have pushed their way into the enterprise, they have brought cloud apps along with them. This app explosion means account passwords are multiplying, which exposes corporate data and leads to help desk calls from frustrated users. This paper will discover how IT can improve user productivity, gain visibility and control over SaaS and mobile apps, and stop password sprawl. Download this white paper to learn: How you can leverage your existing AD to manage app access. Key capabilities to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds