Article

A Fast Track Guide to ASP.NET - Chapter 1

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 Next

Let's take a quick look at a simple example to show how these controls work:

<html>        
     
<script language="VB" runat="server">        
     
Public Sub btn_Click(Sender As Object, E As EventArgs)      
     
' some code goes here End Sub        
     
</script>        
<body>        
<form runat="server">        
     
Press the button: <asp:Button runat="server" Text="Press Me"        
OnClick="btn_Click" runat="server"/>        
     
</form>        
     
</body>        
</html>

The server control in this example is a button, added to the page using the asp:Button element. There are several things to note about this control:

  • It has the runat="server" attribute set, to tell ASP.NET that it should process this control.
  • It uses the Text attribute to set the text to be shown on the button. This is consistent with other controls.
  • It uses the OnClick attribute to identify the event procedure to be run when the button is clicked. Since this is a server control this event procedure runs on the server.

The event procedure is automatically supplied with two parameters -- the control that generated the event, and any additional arguments the procedure requires. Within the event procedure we can access any other server controls, including the contents of input fields submitted during a postback.

HTML Output

In traditional ASP pages, the ASP processor runs server-side code, stripping it out so that only HTML and client-side script is sent to the client. This process is exactly the same for ASP.NET pages (the <% %> tags still work), with the server controls being converted to their HTML equivalents. For example, the page code shown above renders the following HTML to the browser:

<html>        
<body>        
     
<form name="ctrl2" method="post" action="test.aspx" id="ctrl2">        
<input type="hidden" name="__VIEWSTATE"        
value="YTB6MTU5NDYxNjE5Ml9fX3g=2dbab7f5" />      
     
Press the button: <input type="submit" name="ctrl5" value="Press Me" />        
     
</form>        
     
</body>        
</html>

There are several things to note here:

  • The first is that the form has method, action, and id attributes added automatically. We can add these in ourselves (with the exception of the action attribute) if we want to, but it's not necessary.
  • A hidden input field is added, which contains (in a compressed form) the state of the server controls. This is called the ViewState, and is how ASP.NET manages the content of the controls. View State is covered in Chapter 4.
  • The Button is converted into a standard submit button.

So, we can see that even though we have better code on the server, it doesn't affect how the code is presented on the client. It's still standard HTML, with standard forms and elements.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article