You are here

An ASP.NET Tutorial Showing How to Use Buttons on a Web Page

 

ASP.NET is an powerful technology produced by Microsoft. It was originally designed for Windows but it can be used both by the Windows programmer and the Linux programmer. It is useful for a number of reasons such as:

  • The code can be run on the server, hiding from the user;
  • The code is now cross platform (with the correct server software);
  • Web page elements (such as buttons) can be incorporated very easily.

And that's the aim of this ASP.NET tutorial - to show just how easy it is to write ASP.NET for a button.

ASP.NET Tutorial: Creating a Form with a button

The first step is to create a form containing a button (to be clicked by the user) and a label (which will be written to when the button is clicked:

«form runat="server"» «asp:Button id="btn1" runat="server" Text="Say Hello" /» «asp:Label id="lblMessage" runat="server" /» «/form»

It's worth noting the runat="server" statement. This means that any functionality will be carried out on the server (the web host) and not the client (the user's computer).

ASP.NET Tutorial: Adding Code to an ASP.NET Application

Any code that's required is written with a script section and, in this example, the code is written in C# (or C-Sharp):

«%@ Page Language="C#" %» «head» «script runat="server"» public void btn1_Click(Object s, EventArgs e) { lblMessage.Text = "Hello World"; } «/script» «/head»

The runat="server" statement has been used again to ensure that the code is run on the server and not on the client. In this example the code will write some text to a label when the button is clicked.

ASP.NET Tutorial: Assigning an Action to a Button

At the moment the ASP.NET application contains code and it contains a button but the two are not linked. That's done by assigning the C# subroutine to the button. The web developer does this by means of the OnClick event:

«asp:Button id="btn1" runat="server" OnClick="btn1_Click" Text="Say Hello" /»

If this code is saved into an ASP.NET file (for example index.aspx) on suitable server and view using a web browser, then clicking the button will cause the label to be updated.

ASP.NET Tutorial: Protecting the Code

In this example the functionality is fairly simple and limited in scope. However, that functionality can quickly grow. Obviously the programmer will want to protect that code. Fortunately ASP.NET (like PHP) does that automatically. All of the code is stored, and run, on the server. All that's returned to the web browser is the HTML require to display the form (and any required outputs).

In this way the programmer (Windows or Linux) has a powerful and versatile tools with which they can rapidly develop web based applications.

source: suite101