You are on page 1of 10

Your first website

With MS Visual Studio installed, we're ready to create our first ASP.NET website. In VS, this is
very easy. Open the File menu and select "New Web Site". You will be presented with the
following dialog:

You need to select "ASP.NET Web Site", if it's not already selected. You should also name your
new site. This is done by entering a name in the Location box. This text box is probably already
filled for you, with the last part being something like "Website1". You can choose to accept this,
as well as the location of the project, or you can enter a new one, like I did. I have created a
folder, "My Websites", and within this folder, I would like to create the new project with the
name of "FirstWebSite". For now, this is less important, but later on you might wish to gather all
your projects in a specific folder.

This tutorial will focus on the C# language. Once again, no knowledge of this is required, so if
you already know another .NET language, you will get to learn some C# with this tutorial as
well. Select C# in the Language dropdown. Now, click the Ok button to create this new website.
VS will create a very basic website for you, consisting only of a Default.aspx file (and it's
partner, the Default.aspx.cs file) and an App_Data folder. I will explain this later, but for now,
just accept the fact that they are there. We will only use the Default.aspx for this first example.
Move on to the next chapter, for the obligatory "Hello, world!" example.

Hello, world!
In almost every programming tutorial you will find the classic "Hello, world!" example, and who
am I to break such a fine tradition? Let me show you how you can say hello to the world from
ASP.NET. Open the Default.aspx (if it's not already opened) by doubleclicking it in the Solution
Explorer. It already contains a bunch of HTML markup, as well as some stuff you probably won't
recognize, like the Page directive in the top, or the runat attribute on the form tag. This will all be
explained later, but for now, we want to see some working code.
First of all, we will add a Label control to the page. A Label control is some what simple, since
it's just used to hold a piece of text. Add the following piece of HTML-looking code somewhere
between the set of <form> tags:
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>

Secondly, add this script block somewhere on the page, preferably below the Page directive in
the top:
<%
%>

HelloWorldLabel.Text = "Hello, world!";

If you haven't worked with ASP.NET before, I'm sure there's a bunch of things that you're
wondering about now, but as I said, this is all about seeing some results right now. To see the
page in action, use Debug -> Start Without Debugging, or simply press F6. Visual Studio will
now compile your project, and launch the page you're working on in your default browser. The
page will simply have a piece of text which says "Hello, world!" - congratulations, you have just
created your first ASP.NET website! Here is the complete listing:
<%

HelloWorldLabel.Text = "Hello, world!";


%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
</div>
</form>

</body>
</html>

CodeBehind
While our first example was fine, we unfortunately broke one of the coding principles of
ASP.NET: To separate markup and code. As you noticed, we added a scripting block (using <%
%>), where we wrote a line of C# code to use the label. While this is just fine for a small and
simple example like this, we would soon get a real mess with a bunch of C# code within an even
bigger amount of HTML code. If you throw in some JavaScript and some CSS as well, it will
soon become very chaotic to edit. That's why MS introduced CodeBehind, a technique which
allows you to completely separate markup (HTML, CSS etc.) and code (C#, VB.NET etc.). So
let's remove the script block (from <% to %>) and save the file.
As we talked about earlier, VS added a file called Default.aspx.cs. If you can't see it in the
Solution Explorer, then click the little plus sign left of the Default.aspx file. Open this file. Now,
if you haven't worked with .NET or another non-web programming language before, it might
look a bit scary at this point. It looks nothing like HTML. However, I will try to explain the
different parts of the content, and soon you will hopefully see that CodeBehind is a great tool to
get a better overview of your work. Here is a complete listing of the file as it looks right now:
using
using
using
using
using
using
using
using
using

System;
System.Data;
System.Configuration;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}
}

For now, the top part is rather irrelevant to us. It's a list of namespaces being included with the
using keyword, for usage in the file. Since this is an ASP.NET tutorial and not a dedicated C#
tutorial, I won't explain this in depth. Next, we have the class. Classes are a part of the concept of
Object Oriented programming, which has become very popular, especially with languages like
Java and C#. OO is a very complex subject, which also won't be explained within this tutorial.
The name of this class is "_Default", and the : (colon) tells us that this class inherits from the
Page class in the System.Web.UI namespace. This means that our page can already do a bunch of
things, without any programming, because it inherits methods and properties from another class.
All ASP.NET pages inherits from the Page class, or another class which inherits from the Page
class.

The only method within this class is the Page_Load, which is called everytime the page is
loaded. Let's use that to our advantage, and set the ext from this method. We can use the exact
same line of code as before, but of course without the script block tags. Add the line of code
between the { and } characters:
HelloWorldLabel.Text = "Hello, world!";

That's it. Run the project (F6), and have a look. The page looks exactly like before, but we have
just used CodeBehind for the first time. But this example is starting to get a bit old, so in the next
chapter, we will look into something a bit more interesting.

Events
ASP.NET is an event-driven way of making web applications. With PHP and Classic ASP, you
have one file, which is executed line after line, from start to end. However, ASP.NET is very
different. Here we have events, which are either activated by the user in one way or another. In
the previous example, we used the Page_Load method. Actually, this is an event, which the Page
class calls when the page is loaded. We will use the same technique in the next example, where
we will add a couple of controls to our simple hello world example. To make it a bit more
interesting, we will change the "world" word with something defined by the user. Have a look at
this codelisting, where we add two new controls: A Button control and a TextBox control.
<form id="form1" runat="server">
<div>
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
<br /><br />
<asp:TextBox runat="server" id="TextInput" />
<asp:Button runat="server" id="GreetButton" text="Say Hello!" />
</div>
</form>

As you can see, we now have the 2 new controls added, but they really can't do much at the
moment. You can run the example if you wish to check this out for your self - if you click the
button, the page is simply reloaded. Let's change that, and let's start by doing it the easy way. VS
comes with a WYSIWYG editor, and while I hardly ever use it my self, it does make some things
easier, like creating events.
So, click the Design button in the bottom of VS. Now you will see a visual representation of our
page. We wish to add a Click event to the button, and this is very simply - just doubleclick the
GreetButton, and you will be taken to the CodeBehind file of our page. As you can see, a fine
new method has been added, called GreetButton_Click. If you have a look at the Default.aspx
file (you need to go from Design view to Source view), you will see that an attribute has been
added to our Button control, telling which method to call when the button is clicked. All this
work done with a simple doubleclick.
Now lets add some code to our new event. We wish to use the text from the TextBox, on our
good old Label with the "Hello, world!" text. This is also very simple, and all it requires is a
single line of code:
HelloWorldLabel.Text = "Hello, " + TextInput.Text;

Run the project again (F6), and you will see the our old page with a couple of new controls. The
"Hello, world!" text is still there, because we set it in the Page_Load event. Now try entering a

name in the textbox, and press the button. Voila, the text is changed, and we have just used our
first control event. Notice how we can add code which is not necessarily called unless the user
performs a specific task. This is different from the good old Classic ASP/PHP approach, but you
will soon get used to it, and you will probably also come to like it a lot!

More events
Okay, the onclick event from last chapter was easy, but let's try creating all the code required to
use an event from scratch. We will also add yet a new control, to make things more interesting the DropDownList, which allows the user to select an item from a list. Add the folowing code
snippet somewhere in the Default.aspx file:
<asp:DropDownList runat="server" id="GreetList" autopostback="true">
<asp:ListItem value="no one">No one</asp:ListItem>
<asp:ListItem value="world">World</asp:ListItem>
<asp:ListItem value="universe">Universe</asp:ListItem>
</asp:DropDownList>

This thing works just like a normal HTML SELECT element, which is of course what it's
translated into upon rendering. The only attribute that would seem new to a person with basic
HTML experience, is the autopostback. You will learn more about postbacks in one of the next
chapters, but for now, just know that it makes the control contact the server eachtime an item is
selected by the user. We will use this to our benefit now, by adding an event:
<asp:DropDownList runat="server" id="GreetList" autopostback="true"
onselectedindexchanged="GreetList_SelectedIndexChanged">

We are using the onselectedindexchanged event, and assigning a method from CodeBehind
which does not yet exist. You are free to choose the name of the method, but using a convention
with the name of the control, an underscore, and then the name of the event, helps you keep track
of it all. We better go create the event, so change to the Default.aspx.cs file, and add the
following method:
protected void GreetList_SelectedIndexChanged(object sender, EventArgs e)
{
HelloWorldLabel.Text = "Hello, " + GreetList.SelectedValue;
}

Once again, we make this extremely simple. We use the SelectedValue property of our dropdown
list, which holds the text from the value property of the selected item. Try running the site, and
select an item from the dropdown list. Pretty neat, huh? All commen controls come with a bunch
of usefull events, which you can subscribe to like this.

UserControls - Introduction
A UserControl is a separate, reusable part of a page. You can put a piece of a page in a
UserControl, and then reuse it from a different location. The name, UserControl, might seem a
bit fancy, but actually, it's just like a regular page, with an optional CodeBehind file. A notable
difference is that UserControls can be included on multiple pages, while a page can't.
UserControls are used much like regular server controls, and they can be added to a page
declaratively, just like server controls can.

A big advantage of the UserControl is that it can be cached, using the OutputCache functionality
described in a previous chapter, so instead of caching an entire page, you may cache only the
UserControl, so that the rest of the page is still re-loaded on each request.
An example where a UserControl could come in handy, is a control for showing information
about a certain user on a community website. In the next couple of chapters, we will create a
UserControl from scratch, make it fit to our purpose, and then use it on a page.

Creating a UserControl
Okay, so we will be building a UserControl for displaying information about a community user.
First of all, let's add a UserControl to our project. In your Visual Studio, you should be able to
right click on your project and select Add new item.. A dialog will pop up, and you should select
the Web User Control from the list of possible things to add. Let's call our UserControl
UserInfoBoxControl, with the filename of UserInfoBoxControl.ascx. Make sure that you have
checked the checkbox which places code in a separate file, the so-called CodeBehind file.
You should now have a UserInfoBoxControl.ascx and a UserInfoBoxControl.ascx.cs in your
project. The first is where we put our markup, and the second is our CodeBehind file. Now, if
UserInfoBoxControl.ascx is not already open and selected, do so now. You will see only one line
of code, the UserControl declaration. As mentioned, this control will be displaying information
about a user, so let's get started adding some markup to do so:
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="UserInfoBoxControl.ascx.cs" Inherits="UserInfoBoxControl" %>
<b>Information about <%= this.UserName %></b>
<br /><br />
<%= this.UserName %> is <%= this.UserAge %> years old and lives in <%=
this.UserCountry %>

As you can see, it's all very basic. We have a declaration, some standard tags, some text, and then
we have some sort of variables. Now, where do they come from? Well, right now, they come
from nowhere, since we haven't declared them yet. We better do that right away. Open the
CodeBehind file for the UserControl, that is, the one which ends on .cs.
As you can see, it looks just like a CodeBehind file for a regular page, except that it inherits from
UserControl instead of from Page. We will declare the tree properties used in our markup, and
base them on three corresponding fields.
private string userName;
private int userAge;
private string userCountry;
public string UserName
{
get { return userName; }
set { userName = value; }
}

public int UserAge


{
get { return userAge; }
set { userAge = value; }
}
public string UserCountry
{
get { return userCountry; }
set { userCountry = value; }
}

It's all very simple and works just like a regular class. You can even add methods, if you feel like
it! Our UserControl is actually done now, but as you may have already experienced, we can't use
it yet. A UserControl can't be displayed directly in the browser - it has to be included on a page.
We will do that in the next chapter.
Using a UserControl
In the previous chapter we created a UserControl, and now we will try using it for
the first time. Pick a page in your project, or simply create a new one for the
purpose, and open it. The first thing we have to do, is declare our UserControl. It can
be done either in each page where it's used, or globally in the web.config file. There
is no performance difference, but when declaring UserControls in the web.config
file, the controls have to reside in a different directory than the page(s) using it.
For now, let's just declare it within the page. Add the following line below the
standard page declaration:
<%@ Register TagPrefix="My" TagName="UserInfoBoxControl"
Src="~/UserInfoBoxControl.ascx" %>

Make sure that the src value matches the path to your UserControl file. Now you
may use the UserControl in your page, like any other control. For instance, like this:
<My:UserInfoBoxControl runat="server" ID="MyUserInfoBoxControl" />

If you look at the page now, you will see our UserControl in action, although the
information will be a bit... limited. We will have to set a value for the properties we
defined, for things to get just a bit more interestingly. Fortunately, it's very easy:
<My:UserInfoBoxControl runat="server" ID="MyUserInfoBoxControl" UserName="John
Doe" UserAge="45" UserCountry="Australia" />

You see, every public or protected member can be accessed declaretively, allowing
easy access to them when we use our control. However, with this specific
UserControl, chances are that you will be receiving the information from an external
resource, like a database, and then populating the UserControl from there. This
usually involves the CodeBehind of the page, so how can we do that? Pretty simple,
actually. In the CodeBehind of the page, try something like this:
protected void Page_Load(object sender, EventArgs e)
{

// These values can come from anywhere, but right now, we just hardcode

them

MyUserInfoBoxControl.UserName = "Jane Doe";


MyUserInfoBoxControl.UserAge = 33;
MyUserInfoBoxControl.UserCountry = "Germany";

Loading dynamically
Sometimes you may wish to add UserControls to your page dynamically instead of
declaring them. It's actually quite simple too. You need an existing control where
you can add the UserControl to, for instance a Panel. If there's no logical control on
your page to add it to, you may create one for the purpose - the PlaceHolder control
is for situations just like that.
On your page, define it like this:
<asp:PlaceHolder runat="server" ID="phUserInfoBox" />

In the CodeBehind of the page, we add the control like this:


phUserInfoBox.Controls.Add(LoadControl("~/UserInfoBoxControl.ascx"));

We use the LoadControl method to instantiate the UserControl by specifying the


path. This is very easy, but also very anonymous - because we just use the
LoadControl method, we can't really use our own, custom properties. To do that, we
need to make .NET aware of it. On the page, add the following declaration in the
top:
<%@ Reference Control="~/UserInfoBoxControl.ascx" %>

Now we can access the UserInfoBoxControl class like if it were a regular class, which
also means that we can typecast the UserControl returned by the LoadControl
method to this type. In the next example, we do just that, then we set the
properties, and at last, we add it to the PlaceHolder:
UserInfoBoxControl userInfoBoxControl =
(UserInfoBoxControl)LoadControl("~/UserInfoBoxControl.ascx");
userInfoBoxControl.UserName = "John Doe";
userInfoBoxControl.UserAge = 78;
userInfoBoxControl.UserCountry = "Spain";
phUserInfoBox.Controls.Add(userInfoBoxControl);

This will come in handy, for instance when you're adding multiple instances of the
same UserControl to a single page, because you can do it inside a loop.

Events in UserControls
In a previous chapter, we looked at defining properties for our UserControl, but events can be
declared and used as well! This allows you to encapsulate even more functionality inside your
controls, and then let your page respond to certain events, triggered by the control, if necessary.
For this chapter, we will create a new and very simple UserControl, to illustrate how to create
events. It won't have a real life purpose, but is only meant to show you how to use events in a

UserControl. If you don't know how to create and use a UserControl, then please go back a few
chapters. This one will focus on the event part.
First, we create a new, simple EventUserControl, with this code in it:
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="EventUserControl.ascx.cs" Inherits="EventUserControl" %>
Page title:
<asp:TextBox runat="server" ID="txtPageTitle" />
<asp:Button runat="server" ID="btnUpdatePageTitle"
OnClick="btnUpdatePageTitle_Click" Text="Update" />

All just text and server controls that we know. In the CodeBehind, it looks a bit like this:
public partial class EventUserControl : System.Web.UI.UserControl
{
private string pageTitle;
public event EventHandler PageTitleUpdated;
protected void btnUpdatePageTitle_Click(object sender, EventArgs e)
{
this.pageTitle = txtPageTitle.Text;
if(PageTitleUpdated != null)
PageTitleUpdated(this, EventArgs.Empty);
}
public string PageTitle
{
get { return pageTitle; }
}
}

We have defined a pageTitle container variable and a property for it. Then we have a new thing,
an event. As you can see, it's defined much like any other kind of field, but it is a bit different.
The theory about is explained in the C# tutorial, so we won't get into that here.
In the Click event of our button, we set the pageTitle field. Then we check if PageTitleUpdated,
our event, is null. If it's not, it means that we have subscribed to this event somewhere, and in
that case, we send a notification by calling the PageTitleUpdated as a method. As parameters, we
send this (a reference to the UserControl it self) as the sender, and an empty EventArgs
parameter. This will make sure that all subscribers are notified that the pageTitle has just been
updated. Now, in our page, I've declared our UserControl like this:
<%@ Register TagPrefix="My" TagName="EventUserControl"
Src="~/EventUserControl.ascx" %>

And inserted it like this:

<My:EventUserControl runat="server" ID="MyEventUserControl"


OnPageTitleUpdated="MyEventUserControl_PageTitleUpdated" />

As you can see, we have defined an event handler for the PageTitleUpdated event like if it was
any other server control. In the CodeBehind of our page, we define the simple event handler for
the UserControl event like this:

protected void MyEventUserControl_PageTitleUpdated(object sender, EventArgs e)


{
this.Title = MyEventUserControl.PageTitle;
}

It's that simple! Now obviously, updating the page title could have been done directly from our
UserControl, so it's just to provide a simple example on how to use events, but as you will likely
learn later on, this technic will come in handy in lots of situations.
http://asp.net-tutorials.com/validation/required-field-validator/

You might also like