News & UpdatesProgrammingWeb programming Store My Projects

ASP.NET Tutorial – 03 – Hello World

The goal in this section is to create a “Hello World” web application to demonstrate writing, compiling, and running code in ASP.NET.

Label Control

The first step to doing this is to add a Label control inside of the form. This control is used simply to hold a piece of text. Specify the label name using the ID attribute and mark the control to be run on the server.

<asp:Label runat="server" id="myLabel"></asp:Label>

Script Block

Next, add a script block somewhere before the label control. This can be done using the classic ASP delimiter.

<% ... %>

Alternatively, the <script> element, with its language and runat attributes set, can also be used.

<script language="C#" runat="server">...</script>

Control members

Since there is now a label control named “myLabel” defined on the page this control’s members can be accessed by typing the name followed by a dot, inside of the script block. The Intellisense window will then automatically display a list with all of the label’s fields and methods. The member to use for setting the text to be displayed on the label is the “Text” field, so set its value to “Hello World”.

<% myLabel.Text = "Hello World"; %>

Compile and Run

The Hello World program is now complete. To launch it, go up to the debug menu and select “Start Without Debugging” (Ctrl+F5). Visual Studio will then compile the web application and run Internet Explorer to let you view the page. If you open the browser’s page menu and select view source, you can see that all traces of code are gone and only XHTML remain. This is because Visual Studio has launched a web server in the background, which actually executed the web application and sent you the XHTML file. This means that the user’s browser doesn’t need to support any scripting at all to be able view ASP.NET pages. To stop the execution, close the window.

Code Behind

This method of including the script block inside the ASPX file is actually not the preferred method. While it may work fine for small programs it can quickly become difficult to edit and debug the code in larger programs. This is why ASP.NET introduced the “Code Behind” technique, which allows the developer to completely separate the code from the markup. This is what the code file is there for. This file will by default contain a Page_Load method that gets called whenever the web program is run (when the page is viewed). To demonstrate this, take the content from the code block used to change the label and move it to the C# file’s Page_Load method instead.

protected void Page_Load(object sender, EventArgs e) {
  myLabel.Text = "Hello World";

If you now run the web application again you can see that the same text string will get printed as before, but the HTML and C# code are now located in separate source files.

Recommended additional reading:
Sams - Teach Yourself ASP.NET 3.5 in 24 Hours