How is ASP.NET Different from ASP?
This question can be answered in one word – very.
ASP.NET is not just a new version, but a whole new idea and way of programming Web
applications. New features weren't retrofitted into ASP to give us a new version
– ASP.NET has been written from the ground up to provide the best possible
application framework. This has meant that, in many areas, compatibility with ASP
has been broken, but in the long term this is a good thing. It means that ASP.NET
provides a much stronger platform for developing applications, and gives many more
benefits.
If you're worried about the compatibility issue, then remember we mentioned
earlier that ASP.NET runs alongside ASP. Even though there are many differences
between the two, installing ASP.NET won't break existing applications. That's because
your existing ASP pages are still processed by the same mechanism as before, and
the new framework processes ASP.NET pages. This is achieved by ASP.NET pages having
a new file extension (.aspx), meaning they are not processed in the same way as
ASP pages.
Compatibility and migration issues are covered in Chapter 23.
Why Do We Need a New Version?
ASP has achieved enormous success as a way of developing
web sites, so why is a new version needed? Simply put, ASP hasn't evolved to take
into account the way it's now being used. Although designed with great scope and
flexibility, I don't think even its authors could have seen how it would become
the cornerstone of many applications. Like a tempestuous Hollywood starlet, its
rapid rise to fame
has led to problems:
- ASP is a scripted language, relying mainly on VBScript and JScript. Other languages
are available if we install an interpreter, but it's still interpreted. The two
disadvantages of interpreted languages are the lack of strong types (as supported
by typed languages such as Visual Basic and C/C++), and the lack of a compiled environment.
ASP does cache code, but it's still interpreted, and this inevitably leads to performance
and scalability problems.
- ASP doesn't provide an inherent structure for applications. In the days of static
web pages, we used to see small, focused source files. With the dynamic concept
of ASP, it was possible to build code into the web page, again leading to problems.
There's the eternal worry of mixing code and content, which can be a problem if
you have a mixed team, with certain people designing the HTML and the interface,
with different people doing the other coding. Having two sets of people working
on the same files is asking for trouble. Another problem was the ability to make
the code complex, leading to larger source files. Include files allow a certain
amount of structure and code reuse, but it was never really a great solution.
- We have to write code in ASP to do most things, no matter how simple. For example,
consider the task of validating form fields. Just to ensure that values are entered
into a field requires code. Other areas such as caching content, maintaining form
state, and so on, all require code. Even adding new HTML controls requires writing
the raw HTML to the page.
- The world of browser compatibility has morphed into device compatibility. Whilst
the majority of Web access still takes place from a PC and browser, how long will
that remain the case? Mobile devices are becoming more prevalent, and more powerful,
leading to more problems designing sites. If you want your web site to obtain maximum
reach you need to contend with these devices, and this means writing code to detect
the device and render the appropriate content.
-
Standards compatibility also plays a big part in Web development. XHTML is becoming
more widely accepted, XML and XSL/T are both now widely used, and talking to mobile
devices might also mean support for WML. Support for these standards means that
our ASP applications not only have to work with existing standards, but also be
easily upgradeable to support future standards.
These are just some of the problems we will encounter when building
ASP applications, but they aren't the only ones. The rapidly changing nature of
the Internet often requires rapid changes to applications. For languages that have
strong development environments, practices such as componentization, code reuse,
rapid development, and so on, are a great boon to a developer, but this sort of
support is lacking in ASP. The rise of Business-to-Business applications, and peer-to-peer
data sharing also brings great challenges to the developer.
ASP.NET was written from the ground up to meet these needs. Not only
does it answer many of the questions posed by the existing development environment,
but also provides great extensibility, and brings great tool support. At its minimum,
all you require is the ASP.NET redistributable, which is freely available, and you
can continue to use your favorite editor of choice (come on, admit it – it's
Notepad). This gives us access to everything possible with ASP.NET, including multi-language
support. For a richer environment you can use Visual Studio.NET, where you get the
drag and drop support, colored code (more useful than you'd think), context-sensitive
help and tooltips, and all of the usual great editing features that Visual Studio
has brought in the past.
Benefits of ASP.NET
From the above discussion of the problems with ASP it
would be easy to say that ASP.NET solves those problems, and whilst that is so,
there's a lot more to it than that. To understand what's been done, have a look
at four of the main goals of ASP.NET:
- Make code cleaner
- Improve deployment, scalability, security, and reliability
- Provide better support for different browsers and devices
- Enable a new breed of Web applications
You may not see some of this support directly, as the Common Language
Runtime (CLR) handles much of it. This is discussed in detail in the next chapter,
but for now we are going to concentrate on how ASP.NET improves our lives.
Multiple Languages
ASP has been limited to scripting engines, notably VBScript
and JScript. The .NET framework inherently supports multiple languages, so we can
use whichever we feel most comfortable with. Microsoft will support VB.NET, C#,
and JScript (all compiled), and there are a number of third party languages that
we can use, such as managed C++. Because this language support is part of the framework,
it really doesn't matter what language you, or others in your team use. Obviously,
from your point of a view, it's probably best to maintain some degree of compatibility
(for maintenance purposes if nothing else), but as far as the framework is concerned,
anything goes.
This multiple language support isn't just limited to what's available,
but also to how it's used. It's quite possible to write components in one language,
and use (or reuse) them from another language. The server-based controls are written
in C#, but we can quite happily sub-class them from Visual Basic, and then sub-class
that control in JScript (or any .NET supported language).
The framework is covered in more detail in the next chapter, while Chapter 3
delves into the languages themselves in more detail.
Server Processing
If you've done some Visual Basic programming, then you'll
find the switch to the new ASP.NET Server Controls fairly painless, but they might
cause some initial confusion if your programming has been limited to ASP. There's
no need to worry though, as they are extremely easy to understand and use –
it's just that they are very different from ASP.
One of the big problems with ASP is that pages simply define one big
function, which started at the top of the page and finished at the bottom. The page
content is rendered in the page order, whether it is straight HTML or ASP-generated
HTML. Therefore, our logic was dependent upon its position in the page, and there's
no way to target HTML controls except by rendering them as part of the stream. Anything
we do requires us to write code, and that includes the output of HTML elements.
ASP.NET solves this problem by introducing a declarative, server-based
model for controls. This is where the concept may seem alien to ASP programmers,
because the controls are declared on the server, can be programmed against on the
server, but can be event driven from the client. This sounds pretty weird, but it's
simple to use. All we have to do to turn a normal HTML control into a server control
is add runat="server" as an attribute. For example:
<input id="FirstName" type="text"
runat="server">
|
This is a standard HTML control, but the addition of the new attribute
allows the control to be programmed against with server-side code. For example,
if this control is placed within a form and we submit the form back to the same
page, we can do this in our server-side code:
Dim PersonFirstName As String
PersonFirstName = FirstName.Text
|
Making a control run on the server allows us to use the ID attribute
to identify it directly. This allows the code to become more readable, since we
don't have to refer to the form contents or copy the contents into variables. It's
also more natural to refer to the control directly, which makes developing pages
simpler. If you've done any Visual Basic or VBA programming then this won't seem
too alien for you.
If you've only ever done scripting in ASP, then this may seem strange,
but that's only because it's a different way of working with content to and from
the browser. You've probably done database access, so you've used objects, called
methods, and set properties, and the ASP.NET Server Controls aren't really any different
from this.
The new server processing architecture is covered in Chapter 4.
Web Form Controls
Converting existing HTML controls to server-side ones
is simple, but there are still several problems with this approach:
- Consistency. We are still stuck with the rather non-intuitive nature of
some HTML controls. Why for example, is there an INPUT tag for single-line text
entry, but a TEXTAREA tag for multi-line text entry? Surely a single control where
we specify the rows and columns makes more sense?
- User Experience. How do we easily write sites that render rich content
for browsers such as IE, while also preserving compatibility with down level browsers?
HTML doesn't have the ability to change its content depending on the browser –
we have to write the code for that.
- Devices.
How do we write sites that cope with devices other than browsers? WAP-phones, PDAs,
and even fridges have browsers nowadays. Like the browser issue, we'd have to manually
write code for this.
To alleviate these problems Microsoft has created a set of server controls,
identified by the asp: prefix. The ASP.NET server controls tackle the above problems
by:
- Providing a consistent naming standard. For example, all text entry fields are
handled by the TextBox control. For the different modes (multi-line, password, etc.)
we just specify attributes.
- Providing consistent properties. All server controls use a consistent set of properties,
making
- it easier to remember. For example, the Text field of a TextBox is more intuitive
than
a Value field.
- Providing a consistent event model. Traditional ASP pages often have large amounts
of code handling the posting of data, especially when one page provides multiple
commands. With ASP.NET we wireup controls to event procedures, giving our server-side
code more structure.
- Emitting pure HTML, or HTML plus client-side JavaScript. With one minor exception
(which is intentional) the server controls emit HTML 3.2 by default, giving great
cross-browser compatibility. This can be changed so that by default we target up-level
browsers such as IE, where the controls will emit HTML 4.0 and DHTML, providing
a richer interface. All the user ever sees is the HTML content, not the server controls.
- Emitting device-specific code. Certain controls will emit HTML when requested
by a browser, but WML when requested by a WAP-phone. The control handles the detection
of the device and the generation of the correct markup.
The controls will be covered in detail in later chapters, but 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,
with the default post being to the same page. We can add these in ourselves (even
posting to another page) if we want to, but it's not necessary. Letting the server
do this makes the page more readable, as well as allowing us to rename the page
if required, without having to change the action attribute.
- 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. ViewState 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.
Server Control Hierarchy
The server controls are logically broken down into a
set of families:
- HTML Server Controls, which are the server equivalents of the HTML elements.
- Web Form Controls, which map closely to individual HTML elements.
- List Controls, which map to groups of HTML elements that produce grids or grid-like
layout.
- Rich Controls, which produce rich content and encapsulate complex functionality,
and will output pure HTML or HTML and script. A good example of this is the Calendar
control, which provides the user with a calendar from only one line of code.
- Validation Controls, which are non-visible controls, but allow the easy use of
both server-side and client-side form validation.
- Mobile Controls, which output HTML or WML depending upon the device accessing
the page.
Chapters 5 and 6 deal extensively with most of these controls, and Chapter 21
covers the Mobile Controls.
At this early stage in the book, you may not be able to see the implications
that these controls have for you, but let's take a couple of common examples. First
off, the case of displaying data from a database, perhaps in some form of grid.
In ASP, we'd open the Recordset containing the data, and loop through the rows and
columns building up an HTML table. We might well have this abstracted into a separate
function in an include file, but we still had to write the code. With the ASP.NET
DataGrid control, it's the control itself that handles this for us. The list controls
(which include the DataGrid) have built-in support for extracting data from a data
source and creating the HTML for us. For example, consider the following ASP code:
<%
Dim rs
Dim fld
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "select * from authors", _
"Provider=SQLOLEDB; Data Source=.; Initial Catalog=pubs; UID=sa;
PWD="
If Not rs.EOF Then
Response.Write "<table border='1'><tr>"
For Each fld In rs.Fields
Response.Write "<td>" & fld.Name & "</td>"
Next
Response.Write "</tr>"
While Not rs.EOF
Response.Write "<tr>"
For Each fld In rs.Fields
Response.Write "<td>" & fld.Value &
"</td>"
Next
Response.Write "</tr>"
rs.MoveNext
Wend
Response.Write "</table>"
End If
%>
|
There's nothing special about this – it just creates an HTML table.
Now compare this to the equivalent ASP.NET code using a DataGrid:
<%@ Import Namespace="System.Data.SqlClient"
%>
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim con As New SqlConnection("Data Source=.; " & _
"Initial Catalog=pubs; UID=sa; PWD=")
Dim cmd As SqlCommand
con.Open()
cmd = New SqlCommand("select * from authors", con)
DataGrid1.DataSource = cmd.ExecuteReader()
DataGrid1.DataBind()
End Sub
</script>
<asp:DataGrid id="DataGrid1" runat="server"/>
|
We can immediately see how there's much less code to write. In fact,
all of the code here relates to getting the data from the database and binding it
to the grid. There isn't any code to create a table as the DataGrid does this.
Data binding is covered in Chapter 7.
Another great example of the power of controls is the Calendar control,
which with one line of code creates a fully functional calendar on our web page:
<asp:Calendar runat="server"/>
|
That's it – nothing extra is needed to get it working.
This sort of simplified approach doesn't mean that the controls are
simple, just simple to use. The onus on coding has moved from the web page developer
to the control developer. There are also plenty of other non-Microsoft controls,
either planned or released, covering everything from more advanced grids to TreeViews.
Alternatively you can write your own controls. This is covered in Chapter 18.
|