Chapter 1. ASP.NET Web Forms Today

Inspiration is wonderful when it happens, but the writer must develop an approach for the rest of the time. The wait is simply too long.

Leonard Bernstein

In its early years, the Web pushed an unusual programming model and a set of programming tools and languages that were unknown or unfamiliar to the majority of programmers. Anybody who tried to build even a trivial Web site in the 1990s had to come to grips with the HTML syntax and at least the simplest JavaScript commands and objects. That required developing a brand new skill set, which forced people to neglect other, perhaps more productive, activities.

The code and user interface of Web pages—sometimes referred to as the markup mix—had to be written manually in the past decade. And this created a sort of trench separating die-hard C/C++/Java programmers from freaky Web developers. And a growing number of developers using Microsoft Visual Basic were left sitting in the middle and, in some way, were kept from taking a decisive step in either direction—whether it was toward C++ server programming or client Web programming.

Microsoft scored a remarkable victory in the Web industry with the introduction of the ASP.NET platform back in 2001. ASP.NET opened the doors of Web development to a huge number of professionals and contributed to changing the development model of Web applications. ASP.NET wasn’t alone in producing this effort. ASP.NET followed up the progress made by at least a couple of earlier technologies: classic Active Server Pages (ASP) and Java Server Pages (JSP).

So ASP.NET was a success and, more importantly, it has been adopted for nearly any new Web project that has been started in the past decade when targeting the Microsoft platform. Today, ASP.NET is unanimously considered a stable, mature, and highly productive platform for Web development.

Microsoft significantly improved and refined ASP.NET along the way. Today ASP.NET includes a number of extensibility points that weren’t part of it in the beginning. It also offers a rich platform for AJAX development, and built-in controls have been adapted to better support cascading style sheet (CSS) and XHTML requirements.

For a long time, “ASP.NET” just referred to applications written using the Web Forms programming model. More specifically, we could say that ASP.NET refers to the underlying platform and runtime environment whereas “Web Forms” refers to how you create your pages and applications. For about a decade, the two terms mostly were used interchangeably.

A decade is a lot of time, however, especially in the software world. An alternative framework for Web development—ASP.NET MVC—is available these days, and it’s growing and maturing quickly. Is ASP.NET Web Forms still an excellent option for companies developing Web applications? Is the Web Forms model the best model possible? Should we look around for an alternative approach?

While the present book is all about architecting Web applications for the ASP.NET 4 platform and using the Web Forms model, this first chapter offers an annotated overview of the Web Forms model and attempts to outline future developments of Web frameworks for the Microsoft platform.

Note

In this book (and other works of mine), you might sometimes find the term “classic ASP.NET” used to refer to ASP.NET applications written according to the Web Forms programming model. The term is analogous to “classic ASP,” which is often used to distinguish the Active Server Pages technology from ASP.NET Web Forms.

The Age of Reason of ASP.NET Web Forms

ASP.NET was devised in the late 1990s as a way to improve on the current best practices defined by ASP developers. Many of these practices were engineered and baked into a new framework. Even better, the framework was perfectly integrated with the emerging Rapid Application Development (RAD) model that was largely responsible for the success of Visual Basic.

At the time, RAD was coming out as a lightweight, and often more effective, alternative to object-oriented programming (OOP). With a RAD approach supported by visual designers and editors, nearly everybody could quickly and easily prototype, demonstrate, and test an application in a matter of minutes. There was no need for the extra complexity and analysis work required by more theoretical (and bothersome?) approaches like object-oriented design and programming. “You don’t need object-orientation and software principles to write good and effective software on time”—that was the payoff offered by the advertising campaign promoting RAD about a decade ago.

The Original Strengths

The ASP.NET Web Forms model was originally devised to bring the power of RAD to the world of the Web. Hence, the quest for productivity was the primary driving force behind most of the features that still represent the major characteristics and pillars of ASP.NET.

There are three pillars to the Web Forms model: page postbacks, view state, and server controls. They work together according to the model depicted in Figure 1-1.

The Web Forms model in action.

Figure 1-1. The Web Forms model in action.

Each HTTP request that hits the Web server and is mapped to the ASP.NET runtime goes through a number of stages centered on the processing of the postback event. The postback event is the main action that the user expects out of her request.

First, the request is processed to extract preparatory information for the successive postback action. Information includes the state of controls that altogether will produce the final HTML for the page. Following the postback, the HTML response is arranged for the browser, including the new state of controls to be used upon the next request.

All of the server-side steps are wrapped up together according to the definition of the Page Controller pattern. In light of this, each request is seen as processed by a controller entity ultimately responsible for outputting an HTML page. The page controller entity is implemented as a class that fires a few events in the developer’s code, thus giving the developer a way to interact with the request and influence the final output.

To better understand the sense of the Web Forms model and the reasons for its success, look at the following code snippet:

void Button1_Click(Object sender, EventArgs args)
{
   Label1.Text = TextBox1.Text;
}

Defined in a Web Forms class, the Button1_Click function represents the handler of a postback event. When the user clicks the HTML element with a matching ID (in this case, Button1), a request occurs that is resolved by running the code just shown. If it weren’t for the stateless nature of the Web protocols, this would be like the standard event-driven programming model that many of us used (and enjoyed) in the early Visual Basic days of the late 1990s.

In the body of the handler method, you can access in a direct manner any other page elements and set its state accordingly as if you were just touching on the user interface. Interestingly enough, though, the preceding code runs on the Web server and needs a bit of extra work to mediate between the client HTML and the server environment. But it works, and it is easy—extraordinarily easy—to understand and apply.

Page Postbacks

An ASP.NET page is based on a single form component that contains all of the input elements the user can interact with. The form can also contain submission elements such as buttons or links.

A form submission sends the content of the current form to a server URL—by default, the same URL of the current page. The action of posting content back to the same page is known as the postback action. In ASP.NET, the page submits any content of its unique form to itself. In other words, the page is a constituent block of the application and contains both a visual interface and some logic to process user gestures.

The click on a submit button or a link instructs the browser to request a new instance of the same page from the Web server. In doing so, the browser also uploads any content available in the (single) page’s form. On the server, the ASP.NET runtime engine processes the request and ends up executing some code. The following code shows the link between the button component and the handler code to run:

<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" />

The running code is the server-side handler of the original client-side event. From within the handler, the developer can update the user interface by modifying the state of the server controls, as already shown and as reiterated here:

public void Button1_Click(object sender, EventArgs args)
{
    // Sets the label to display the content of the text box
    Label1.Text = "The textbox contains: " + TextBox1.Text;
}

At the time the handler code runs, any server controls on the page have been updated to hold exactly the state they had during the last request to the page, plus any modifications resulting from posted data. Such stateful behavior is largely expected in a desktop scenario; in ASP.NET, however, it requires the magic of page postbacks.

The View State

The view state is a dictionary that ASP.NET pages use to persist the state of their child controls across postbacks. The view state plays an essential role in the implementation of the postback model. No statefulness would be possible in ASP.NET without the view state.

Before ASP.NET, in classic, VBScript-based ASP, developers frequently used hidden fields to track critical values across two successive requests. This approach was necessary when multiple HTML forms were used in the page. Posting from one would, in fact, reset any values in the fields within the other. To make up for this behavior, the values to track were stored in a hidden field and employed to programmatically initialize fields during the rendering of the page.

The view state is just an engineered and extended version of this common trick. The view state is a unique (and encoded) hidden field that stores a dictionary of values for all controls in the (unique) form of an ASP.NET page.

By default, each page control saves its entire state—all of its property values—to the view state. In an average-sized page, the view state takes up a few dozen KBs of extra data. This data is downloaded to the client and uploaded to the server with every request for the page. However, it is never used (and should not be used) on the client. The size of the view state has been significantly reduced over the years, but today the view state is still perceived as something that has a heavy impact on bandwidth.

It is definitely possible to write pages that minimize the use of the view state for a shorter download, but the view state remains a fundamental piece of the ASP.NET Web Forms architecture. To eliminate the view state from ASP.NET, a significant redesign of the platform would be required.

ASP.NET 4 introduces new features that deliver to developers more control over the size of the view state without compromising any page functionality.

Server Controls

Server controls are central to the ASP.NET Web Forms model. The output of an ASP.NET page is defined using a mix of HTML literals and markup for ASP.NET server controls. A server control is a component with a public interface that can be configured using markup tags, child tags, and attributes. Each server control is characterized by a unique ID and is fully identified by that.

In the ASP.NET page markup, the difference between a server control and a plain HTML literal string is the presence of the runat attribute. Anything in the source devoid of the runat attribute is treated as literal HTML and is emitted to the output response stream as is. Anything flagged with the runat attribute is identified as a server control.

Server controls shield developers from the actual generation of HTML and JavaScript code. Programming a server control is as easy as setting properties on a reusable component. When processed, though, the server control emits HTML. In the end, programming server controls is a way of writing HTML markup without knowing much about its unique syntax and feature set.

Server controls consume view state information and implement postback events. In addition, server controls are responsible for producing markup and do that without strictly requiring strong HTML skills on your end.

Today’s Perceived Weaknesses

In the beginning of ASP.NET Web Forms, requiring very limited exposure to HTML and JavaScript was definitely a plus. However, the bold advent of AJAX in the middle of the past decade modified the perspective of Web applications and, more importantly, significantly changed user expectations of them. As a result, much more interaction and responsiveness are required.

To increase the degree of responsiveness of Web applications, you can increase the amount of script code that runs within the browser only when a given page is being displayed. This simple fact raised the need for developers to gain much more control over the actual markup being sent out.

More Control over HTML

To code AJAX features, developers need to make clear and reliable assumptions about the structure of the Document Object Model (DOM) displayed within the browser. It turns out that smart black boxes, which are what ASP.NET server controls were initially conceived as, are no longer ideal tools to build Web pages.

Developers need to be sure about the layout of the HTML being output; likewise, developers need to control the ID of some internal elements being inserted into the resulting DOM. The adoption of the Web model in a large area of the industry and the public sector has resulted in the creation of applications with a potential audience of a few million people—not necessarily power users, perhaps users with disabilities, and not necessarily users equipped with the latest version of a given browser. And still developers are tasked with ensuring that all of this heterogeneous audience has the best experience and a common interface.

As you can see, the advent of AJAX brought about the complete turnaround of one of the ASP.NET pillars. Originally designed to favor independence from HTML, ASP.NET is now asked to favor a programming model that heralds total control over HTML. As you’ll see in the rest of the book, although this is far from being a mission-impossible task, it requires you to pay much more attention to how you configure controls and design pages. It also requires you, on your own, to attain a lot more awareness of the capabilities of the platform.

Separation Between Processing and Rendering

ASP.NET made the Web really simple to work with and made every developer a lot more productive. To achieve this result, ASP.NET was designed to be UI focused. All you do as a page developer is author pages and the code that runs behind the page.

The page gets input; the page posts back; the page determines the output for the browser. The underlying model leads you to perceive any requests simply as a way to generate HTML through a page. The page entity dwarfs anything else; you don’t really see any correspondence between a request and a subsequent server action. All you see is an incoming HTTP request and a server page object that takes care of it and returns HTML.

In this model, there’s no clear separation between the phase of processing the request to grab raw data to be incorporated in the response (for example, a list of records to be displayed in a grid) and the phase of formatting the raw data into an eye-catching, nice-looking layout.

Again, you’ll see in the rest of the book that achieving separation between processing and rendering is definitely possible in ASP.NET Web Forms and is not at all a mission-impossible task. However, it requires that you pay a lot more attention and have more discipline when it comes to writing pages and the code behind pages. Figure 1-2 extends the schema of Figure 1-1 and provides a more detailed view of the page-based pattern used to process requests in ASP.NET Web Forms. (I’ll return in a moment to the Page Controller pattern.)

ASP.NET request processing and HTML rendering.

Figure 1-2. ASP.NET request processing and HTML rendering.

The entire processing of an HTTP request is done by progressively updating the state of the server controls the page is made of. At the end of the cycle, the current state of controls is flushed to the response output stream and carried to the browser. The entire cycle is based on the idea of building a page, not performing an action and showing its results.

For years, this aspect of Web Forms was just accepted for what it was, with no special complaints and some praises. Today, the growing complexity of the business logic of applications built on top of the ASP.NET platform raises the need for unit tests and static analysis that are harder to set up in a runtime environment strongly focused on the plain UI.

Again what was a huge winning point in the beginning is now slowly turning into a significant weakness.

Lightweight Pages

The view state is a fundamental element of the ASP.NET puzzle because it allows for the simulated statefulness of the Web Forms model. Many developers who recently embraced ASP.NET MVC—the alternate framework for ASP.NET development fully integrated in Visual Studio 2010—still find it hard to understand that each view can have shared data that must be refilled even though nothing in the request processing happened to modify it. More simply, it is the lack of view state that keeps any UI element (grids, drop-down lists, and text boxes) empty until explicitly filled on each and every request.

The view state has always been a controversial feature of ASP.NET. Starting with ASP.NET 2.0 (some five years ago), however, Microsoft introduced significant changes to the internal implementation of the view state and reduced the average size of the view state hidden field by a good 40 percent.

The view state is functional only to an application model extensively based on server controls and using server controls extensively to generate HTML. At a time when architects question the applicability of the classic ASP.NET model to their applications and look for more client-side interaction, separation of concerns (SoC), and control over the markup, the view state feature—a pillar of ASP.NET—is not that significant. Hence, it is now, more than ever, perceived as deadweight to get rid of.

Important

More and more applications require pages rich with client code that limit the number of postbacks and replace many postbacks with AJAX calls. In this context, Web Forms can be adapted—maybe even to a great degree—but the approach has some architectural limitations that must be known and taken into account. These limitations are not necessarily something that would make you lean toward an alternate framework such as ASP.NET MVC, but they also are not something a good architect can blissfully ignore.

How Much Is the Framework and How Much Is It You?

Introduced a decade ago, ASP.NET Web Forms has evolved and has been improved over the years. Its flexible design allowed for a lot of changes and improvements to be made, and the framework is still effective and productive. Although the design of the ASP.NET framework was inspired by a totally different set of principles and priorities than the ones you would apply today, most of the alleged limitations of ASP.NET that I’ve outlined so far (heavyweight pages, limited control over markup, lack of testability) can still be largely worked out, smoothed over, and integrated to serve up an effective solution. This is to say that the advent of a new framework such as ASP.NET MVC doesn’t necessarily mean that ASP.NET Web Forms (and, with it, your existing skills) are out of place. There’s always a strong reason for new things (frameworks in this regard) to be developed, but understanding needs, features, and capabilities is still the only proven way of dealing with hard decisions and architecture.

ASP.NET Web Forms is designed around the Page Controller pattern. Let’s find out a bit more about the pattern and what you can do to limit some of its current downsides.

The Page Controller Pattern

The ASP.NET Web Forms model resolves an incoming request by dispatching the request to an HTTP handler component. (An HTTP handler component is simply a class that implements the IHttpHandler interface.) According to the ASP.NET Web Forms model, the HTTP handler is expected to return HTML for the browser. (You’ll find out more about HTTP handlers in Chapter 4.) The way in which the HTML for the browser is prepared is strongly oriented to the creation of a Web page. The pattern behind this approach is the Page Controller pattern.

The pattern envisions the processing of a request as a task that goes through a number of steps, such as instantiating the page, initializing the page, restoring the page’s state, updating the page, rendering the page, and unloading the page. Some of these steps have been rendered in Figure 1-2, and all of them will be discussed in detail in Chapter 2 and in Chapter 3.

In the implementation of the pattern, you start from a base page class and define a strategy to process the request—the page life cycle. In the implementation of the page life cycle, you come up with an interface of virtual methods and events that derived pages will have to override and handle. (See Figure 1-3.)

The internal page life cycle exposed to user code via page controller classes.

Figure 1-3. The internal page life cycle exposed to user code via page controller classes.

Derived page classes are known as code-behind classes in ASP.NET jargon. Writing an ASP.NET page ultimately means writing a code-behind class plus adding a description of the user interface you expect for it. The code-behind class is the repository of any logic you need to serve any possible requests that can be originated by the input elements in the page. A code-behind class derives from a system class—the System.Web.UI.Page class.

Taken individually, a code-behind class is simply the “controller” object responsible for processing a given request. In the context of an application, on the other hand, it can lead you to building a small hierarchy of classes, as shown in Figure 1-4.

A sample hierarchy of classes.

Figure 1-4. A sample hierarchy of classes.

Your code-behind class can inherit from the system base class or from intermediate classes with a richer behavior. Developers can extend the hierarchy shown in the figure at will. Especially in large applications, you might find it useful to create intermediate page classes to model complex views and to fulfill sophisticated navigation rules. Building a custom hierarchy of page classes means placing custom classes in between the page controller and the actual code-behind class.

The ultimate reason for having a custom hierarchy of pages is to customize the page controller, with the purpose of exposing a tailor-made life cycle to developers. An intermediate class, in fact, will incorporate portions of common application behavior and expose specific new events and overridable methods to developers.

Revisiting the Page Controller Pattern

Today the main focus of Web architectures is more oriented toward the action rather than the concrete result. This is essentially because of a paradigm shift that generalized the use of the Web tool—it’s no longer just a way to get HTML pages but is a lower level producer of data with its own (variable) representation.

To serve the needs of the new Web, you probably don’t need all the thick abstraction layer that purposely was added on top of the Web Forms model ten years ago with the precise goal of simplifying the production of the sole conceivable output—the HTML page.

A framework like ASP.NET MVC—even though it is built on the same runtime environment as ASP.NET Web Forms—will always adhere more closely than ASP.NET Web Forms to the new paradigm. It’s a matter of structure, skeleton, and posture; it’s not a matter of gesture or behavior. However, there’s some room for teams of developers to revisit the Web Forms model and change its posture to achieve benefits in terms of both testability and separation of concerns.

Revisiting the Page Controller pattern today means essentially taking into account design patterns that privilege separation of concerns between involved parts of the system. This probably doesn’t mean that you can rearrange the entire page life cycle—you need a new framework for that similar to ASP.NET MVC—but you can restructure some portions of the page life cycle to isolate portions of code as distinct components that are testable and writable in isolation.

For example, revisiting the Page Controller pattern means applying the Model View Presenter (MVP) pattern to decouple the implementation of the postback mechanism with the subsequent rendering of the view. We’ll get back to this topic in Chapter 15.

In the end, in the second decade of the 2000s ASP.NET Web Forms is approaching an architectural dead end. On one hand, it is recommended that you do not unconsciously ignore newer frameworks (for example, ASP.NET MVC); on the other hand, however, Web Forms is still highly effective, mature, and functional and certainly doesn’t prevent you from achieving great results.

Whether you’re considering shifting to ASP.NET MVC or sticking to Web Forms, it is essential that you reconsider the design and architecture of your views and pages. The classic Page Controller pattern is getting obsolete and needs solutions to make it more testable and layered. An effective Web Forms application today needs separation of concerns, interface-based programming, and cohesive components. No framework will give you that free of charge, but with Web Forms you need a great deal of awareness and commitment.

The AJAX Revolution

Like it or not, the Web is changing, and this time it is changing for developers and architects. In the evolution of software, we first observe a spark of genius triggering an innovative process and the teaching of new tricks and new ways of doing things. In this case, it was the spark of AJAX and the need to build effective and rich user experiences. Next, developers start generalizing and abstracting things to make them reusable and easy to replicate repeatedly in a variety of scenarios. When this happens, we have a paradigm shift.

Today we are moving away from many of the ideas and pillars of Web Forms. It’s not a process that has a well-known and defined completion date yet, but nobody doubts that such a day is in our near future.

The spark of AJAX was just the realization that we can place out-of-band requests, bypass the classic browser machinery, and gain total control of the request and subsequent response. Is this just a little, geeky detail? Maybe, but this little detail triggered a huge transformational process—an entire paradigm shift—whose results will be clear and definitive only in a few years. That’s my guess, at least. Let’s briefly consider what paradigm shifts are and what they mean (and have meant) to humans throughout history.

Moving Away from Classic ASP.NET

As drastic as it might sound, the Web revolutionized the concept of an application. Now AJAX is revolutionizing the concept of a Web application. The Web will always remain separate from the desktop, but Web applications are going to enter a new age.

What’s a Paradigm Shift?

According to Wikipedia, a paradigm shift describes a change in most of the basic assumptions within the ruling theory of a science. The shift creates a break and clearly contrasts with the current ideas and approaches. A paradigm shift is a long process that begins naturally when enough significant limitations and anomalies have been found within the current state of the art in a discipline.

At this point, new ideas are tried—often ideas that were considered years before and then discarded. The community proceeds by trial and error, experimenting and trying to come to general conclusions. Inevitably, a paradigm shift puts the discipline into a state of crisis. (This is the term used by Thomas Kuhn, who coined the term paradigm shift and formalized these concepts.) The state of crisis manifests itself through a number of attempts to change, each presented as possibly definitive but that hardly work for everybody, at least in the original form.

The impact of a paradigm shift is particularly deep in areas that appear to be stable and mature. A great example of a paradigm shift is the changes in physics at the beginning of the twentieth century. Before the advent of Einstein’s theory of relativity, physics was unanimously considered to be a largely worked-out system. The theory of relativity he formulated in 1905 changed everything in the field, but it was only about three decades later that the process of redefining the fundamentals of physics was completed. For more information, pay a visit to http://en.wikipedia.org/wiki/Paradigm_shift. It’s definitely illuminating reading.

So now, how does this apply to ASP.NET and AJAX?

The AJAX Paradigm Shift

Even though we tend to date the advent of AJAX around the 2004, one of the core tools of AJAX—the XmlHttpRequest object—is much older. In the late 1990s, we already had all the technologies we are using today to set up AJAX solutions. For a number of reasons, the idea of using JavaScript, the HTML DOM, and the XmlHttpRequest object to update pages asynchronously was discarded for most applications, even though Outlook Web Access and a number of niche applications continued using it.

It was tried again in the early 2000s, and this time it really stuck.

Like physics in the early twentieth century, ASP.NET Web Forms was a stable and mature platform when AJAX experiments started. In the beginning, it was simply a matter of spicing up some pages with a piece of JavaScript code and downloading raw data from an HTTP endpoint. However, it is one thing to download a number or a string and refresh the small portion of the user interface that contains it, but it’s quite another to download a collection of data objects to repopulate a grid. And what if you intend to post the content of a form and then update a large section of the current view?

The underlying machinery and tools remain the same, but the way in which they are organized, exposed to developers, and consumed requires a lot of thinking and perhaps a brand new application model.

In particular, the advent of AJAX raised the need for developers to embed more JavaScript code in HTML pages. The JavaScript code, however, has to deal with HTML DOM elements, each of which is commonly identified with a unique ID. In an ASP.NET Web Forms application, it’s the set of server controls defined in a page that ultimately determines the structure of the HTML DOM and the ID of the constituent elements.

To support AJAX deeply and effectively, Web Forms developers have to dig out some of the internal details of the server control black boxes. In doing so, developers attack one of the pillars of the Web Forms model. The more AJAX you want, the more control you need over HTML; the more control over HTML you want, the more you are mining the foundation of ASP.NET Web Forms.

But there’s more than just this.

The Data-for-Data Model

For years, the Web worked around a Pages-for-Forms model. It was just fine in the beginning of the Web age when pages contained little more than formatted text, hyperlinks, and maybe some images. The success of the Web has prompted users to ask for increasingly more powerful features, and it has led developers and designers to create more sophisticated services and graphics. As a result, today’s pages are heavy and cumbersome. (See Figure 1-5.)

A page sends out the content of an HTML form and receives an HTML page.

Figure 1-5. A page sends out the content of an HTML form and receives an HTML page.

Given the current architecture of Web applications, each user action requires a complete redraw of the page. Subsequently, heavier pages render out slowly and produce a good deal of flickering. Projected to the whole set of pages in a large, portal-like application, this mechanism is perfect for causing great frustration to the poor end user.

AJAX just broke this model up. A request might or might not post a form and request an entire page. More often, an HTTP request might just pass raw data and request raw data—an overall simplification of the interaction model. (See Figure 1-6.)

HTML elements fire out-of-band calls passing raw data and getting raw data, not necessarily HTML pages.

Figure 1-6. HTML elements fire out-of-band calls passing raw data and getting raw data, not necessarily HTML pages.

ASP.NET Web Forms was created to receive forms and return pages. It is difficult to turn it into a model that fully supports the Data-for-Data model of AJAX. Web Forms hides a lot of its machinery and offers a higher level view of the Web operation than many demand today.

This fact can’t be ignored when making architectural decisions about which platform to use for a given Web project.

It’s not relevant whether Web Forms was designed in the wrong or right way. It was right for the time it was designed. The advent of AJAX created different business conditions; in these conditions, Web Forms is not necessarily the ideal framework.

But is there any ideal ASP.NET framework out there?

What Web Do We Want for Developers?

A decade ago, we just wanted applications deployed through the Web. And Web Forms worked just fine to satisfy us. Later on, we wanted richer applications that were quicker and smoother to use and more responsive. And a good set of AJAX capabilities added to Web applications made us happier as end users.

What about developers?

We probably completed the step of understanding what kind of Web applications we want to serve to our users. We don’t yet have an effective set of developer tools to make the creation of modern Web applications quick, easy, and productive—in one word, effective. So we’re in search of the perfect framework. Developers need to build user interfaces to be served and consumed over the Web and within a Web browser. Such a framework must simplify a number of common tasks. Here’s a list of the capabilities we expect:

  • The user interface must be dynamic and adjust itself as the user interacts. This means, for example, hiding or showing panels and buttons as the user makes a choice.

  • The user interface must be responsive and perform quick cross-checks on data displayed, and it must perform remote validation whenever possible and required.

  • It should be possible to start a remote operation and update the current view even with a new user interface if necessary.

  • It should be possible to display dialog boxes on top of the existing pages.

  • It should be possible to request data for remote application-specific endpoints.

In terms of technologies, we definitely need a rich client infrastructure, a simple controller component to parse HTTP requests and dispatch commands to the back end, and we need a layered architecture to keep business tasks separate from presentation and data access.

The development team is directly responsible for the architecture and for adding as many layers as they think are necessary. The framework, on the other hand, should simplify the other aspects and provide smooth integration between client and server code and naturally and effectively process the incoming requests. We don’t yet have the perfect framework. It will probably take a couple more years for this to materialize. But we see all around signs of libraries and tools being consolidated.

The family of jQuery libraries (including the jQuery UI library and various plug-ins) seems to be the catalyst for dynamic user interfaces; ASP.NET MVC seems to be the simpler framework to start with and to build new made-to-measure abstractions. Abstraction is still important because it’s only via abstraction that you build productivity.

Whatever emerges as the ideal ASP.NET framework for the next decade, my guess is that it will build on jQuery and most of the principles and solutions in ASP.NET MVC. ASP.NET Web Forms today is in the middle of a transition. It is neither the future nor the past. It can be adapted and still be effective. It requires an awareness of the changes, in business and subsequently architecture, we are experiencing.

AJAX as a Built-in Feature of the Web

The biggest challenge of ASP.NET development today is unifying the programming model, which is currently split in two: ASP.NET Web Forms on one side and ASP.NET MVC on the other side. The biggest challenge of Web development in general, though, is removing the label “AJAX” from the term “Web.”

Because it started such a huge paradigm shift, AJAX can’t simply be considered an umbrella term to refer to a specific set of software capabilities. AJAX today is a constituent part of the Web. We would like to be able to write the next generation of Web applications using a framework in which AJAX is just part of the deal. You might be asked to configure it once, and then enjoy it free of charge and without any additional cost of writing specific code.

As a built-in feature of a Web framework, AJAX requires you to have an API to code against that just does AJAX without needing developers to think about it. ASP.NET offered a common and familiar programming model for writing Web applications, and this was one of the keys to its rapid adoption. Before ASP.NET, there were various ways of writing Web applications and different tools. You had to choose the tool beforehand and adapt to its vision of the Web. Today with AJAX, we are experiencing something similar. You have an AJAX API in ASP.NET Web Forms based on a technology known as partial rendering; you have the possibility of defining ASP.NET endpoints and exposing them as Web services; you have similar technologies in ASP.NET MVC; you have direct scripting via jQuery and a bunch of other JavaScript libraries. We don’t have yet a unique (and updated) model for doing Web development with AJAX in it. AJAX changed the Web; now we want a framework for writing Web applications with AJAX built inside.

Selective Updates

Basically, there are two ways in which you can incorporate AJAX into a Web framework. I like to refer to them as selective updates and direct scripting.

You perform a selective update when you execute a server action and then return a chunk of HTML to selectively update the current view. This approach descends from the HTML Message AJAX pattern as summarized at http://ajaxpatterns.org. The trick is all in bypassing the browser when a request—form post or hyperlink—has to be submitted. You place a script interceptor at the DOM level (for example, a handler for the Form DOM object submit event), capture the ongoing request, cancel the operation, and replace it with your own asynchronous implementation. When a response is received, it is assumed to be HTML and integrated into the current DOM at a given location.

An ASP.NET framework that fully supports the Selective Update model will specify details for how the script interceptor has to be defined and for how the current view has to be modified. In ASP.NET Web Forms, the Selective Update model is implemented via partial rendering. In ASP.NET MVC, it comes through the services of the AJAX HTML helper.

Direct Scripting

Direct scripting is plain JavaScript code through which you connect to a remote endpoint to send and receive data. You likely rely on a rich JavaScript framework (for example, jQuery) and use the JSON format to move complex data around.

In my opinion, the Direct Scripting model is good for little things that can improve a feature of the user interface. I don’t see the Direct Scripting model growing to become the reference pattern for AJAX applications. To be effective, direct scripting requires an ad hoc architecture and a new set of standards. Rich Internet Application (RIA) services and open protocols such as Open Data (oData) and Open Authorization (oAuth) are coming out, but direct scripting remains an option for a subset of sites and applications.

I wouldn’t pick up direct scripting as the solution for a unified programming model that accommodates the server-side Web and the client-side Web. Why not? With direct scripting, you are indissolubly bound to JavaScript and HTML. This is certainly great for some applications, but not for all.

To achieve direct scripting capabilities, today you have to look in the direction of the jQuery library and its plug-ins. I’ll cover jQuery in Chapter 21.

ASP.NET of the Future

ASP.NET 4 is the latest release of the ASP.NET framework that has seen the light in the same timeframe as Visual Studio 2010. As expected, ASP.NET 4 comes with a number of improvements mostly in the area of controlling the markup served by controls. You also find in ASP.NET 4 a richer caching API, routing support, further extensions of the provider model, and a few new server controls.

If you try to weigh out the new features in the framework, you probably find enough to justify a new release, but not necessarily a fundamental release in the history of the product. Why is this so?

As mentioned, ASP.NET as we’ve known it for a decade is really approaching an architectural dead end. There’s not much else that can be added to the Web Forms model; likewise, there are a few aspects of it that sound a bit obsolete today, but changing them would require a significant redesign of the system. From here, the following question arises: What will be the ASP.NET of the future?

Will it be just a further improved version of ASP.NET MVC? Will it be Web Forms with some built-in infrastructure that makes it easier to write testable and layered code? If I look into the future of ASP.NET, I see big two challenges:

  • Having AJAX on board without calling for it

  • One ASP.NET platform that offers testability, simplicity, layering, control, styling, AJAX, and productivity

Nothing is in sight yet at the moment that handles both challenges. So we’re left with using ASP.NET Web Forms the best we can and exploring alternatives. The entire book is devoted to examining ways to write smarter and better ASP.NET Web Forms code. For now, let’s briefly explore two alternatives.

ASP.NET MVC

With version 2 released at the same time as ASP.NET 4 (and version 3 released by the time you read this book), ASP.NET MVC is a good candidate to find a place in the sun in the ASP.NET arena. As clearly stated by Microsoft, ASP.NET MVC is not the successor to Web Forms. It is rather a fully fledged, and fully qualified, alternative to Web Forms. Each framework has its own set of peculiarities. At the end of the day, it is difficult, and also kind of pointless, to try to decide objectively which one is better.

Choosing between ASP.NET Web Forms and ASP.NET MVC is essentially a matter of personal preference, skills, and of course, customer requirements. As an architect or developer, however, it is essential that you understand the structural differences between the frameworks so that you can make a thoughtful decision.

ASP.NET MVC Highlights

ASP.NET MVC is a completely new framework for building ASP.NET applications, designed from the ground up with SoC and testability in mind. With ASP.NET MVC you rediscover the good old taste of the Web—stateless behavior, full control over every single bit of HTML, and total script and CSS freedom.

Processing the request and generating the HTML for the browser are distinct steps and involve distinct components—the controller and the view. The controller gets the request and decides about the action to take. The controller grabs the raw response and communicates it to the view engine for the actual writing onto the browser’s output stream.

In ASP.NET MVC, there’s no dependency on ASPX physical server files. ASPX files might still be part of your project, but they now serve as plain HTML templates that the default view engine uses as a template for creating the HTML response for the browser. When you author an ASP.NET MVC application, you reason in terms of controllers and actions. Each request must be mapped to a pair made by a controller and an action. Executing the action produces data; the view engine gets raw data and a template and produces the final markup (or whatever else it is expected to produce, such as JSON or JavaScript). Figure 1-7 shows the sequence of steps that characterize a typical ASP.NET MVC request.

The sequence diagram for an ASP.NET MVC request.

Figure 1-7. The sequence diagram for an ASP.NET MVC request.

A Runtime for Two

The runtime environment that supports an ASP.NET MVC application is largely the same as in ASP.NET Web Forms, but the request cycle is simpler and more direct. An essential part of the Web Forms model, the page life cycle, is now just an optional implementation detail in ASP.NET MVC. Figure 1-8 compares the run time stack for Web Forms and ASP.NET MVC.

The run-time stack of ASP.NET MVC and Web Forms.

Figure 1-8. The run-time stack of ASP.NET MVC and Web Forms.

As you can see, the run-time stack of ASP.NET MVC is simpler and the difference is due to the lack of a page life cycle. As mentioned earlier, the page life cycle and the entire thick abstraction layer built by Web Forms saves the developer a lot of work.

ASP.NET MVC is closer to the metal, and this has its own side effects. If you need to maintain state, that is up to you. For example, you can store it into Session or Cache, or you can even create, guess what, your own tailor-made, view state–like infrastructure. In the end, the simplicity of ASP.NET MVC is due to different architectural choices rather than to some overhead in the design of the Web Forms model.

So ASP.NET MVC brings to the table a clean design with a neat separation of concerns, a leaner run-time stack, full control over HTML, an unparalleled level of extensibility, and a working environment that enables, not penalizes, test-driven development (TDD).

ASP.NET Web Forms and ASP.NET MVC applications can go hand in hand and live side by side in the same process space. The runtime environment must be configured to host an ASP.NET MVC application. This means installing a routing module that intercepts requests at the gate and decides how they are to be processed. An ASP.NET MVC application lists one or more URL patterns it will accept. Requests whose URL matches any defined patterns are processed as ASP.NET MVC requests, while others are left to the standard processing engine of Web Forms.

Control over Markup

Just like with Web Forms, what some perceive as a clear strength of ASP.NET MVC, others may see as a weakness. ASP.NET MVC doesn’t offer server controls of its own and also severely limits the use of classic ASP.NET server controls. Even though you describe the view of an ASP.NET MVC page via ASPX markup, you can’t embed in it server controls that handle postbacks. In other words, you are allowed to use a DataGrid if your goal is creating a table of records, but your code will receive an exception if the DataGrid is configured to allow paging, sorting, or inline editing.

To gain full control over HTML, JavaScript, and CSS, ASP.NET MVC requires that you write Web elements manually, one byte after the next. This means that, for the most part, you are responsible for writing every single <li> or <table> tag you need. In ASP.NET MVC, there’s no sort of component model to help you with the generation of HTML. As of today, HTML helpers and perhaps user controls are the only tools you can leverage to write HTML more quickly. Overall, some developers might see ASP.NET MVC as taking a whole step backward in terms of usability and productivity.

Adding visual components to ASP.NET MVC is not impossible per se; it is just arguably what most users of the framework really want. My opinion is that keeping any form of markup abstraction far away from ASP.NET MVC is OK as long as you intend to have two distinct frameworks for ASP.NET development. But I do hope that we move soon to a new framework that unifies the Web Forms and ASP.NET MVC models. In this new framework, if it ever arrives, I do expect some markup abstraction as the only way to increase productivity and have people move to it.

ASP.NET MVC and Simplicity

Simplicity is a characteristic that is often associated with ASP.NET MVC. If you look at Figure 1-8, you can hardly contest the point—ASP.NET MVC is architecturally simpler than Web Forms because the sequence of steps to process a request follows closely the rules of the underlying protocols, with no abstractions created by the framework.

This is a correct statement, but it is a bit incomplete. ASP.NET MVC processes a request through an action and passes return values to a view engine. In doing so, though, ASP.NET MVC offers a number of free services that you might or might not need. For example, when a form posts its content, the framework attempts to bind posted data to the formal parameters of the action method in charge of serving the request. There’s a lot of reflection involved in this approach, and some work is done that might not strictly be needed. Can you opt out of this model binding, and how easy is it to do so?

This is the point that shows why ASP.NET MVC targets simplicity in a much more effective way than Web Forms.

In ASP.NET MVC, opting out of a built-in feature simply requires that you use a different coding convention. There’s nothing to disable and no closure to crack open to get a different behavior. Any complexity in ASP.NET MVC is built in a bottom-up manner, by composing layers of code one on top of the other. At any time, you can step back and remove the topmost layer to replace it or simply do without it.

In Web Forms, opting out of any built-in feature is much harder because the framework was deliberately built around them in a top-down manner. You can still create HTML-based pages in Web Forms, but it will be significantly hard and counterintuitive. To alter the default behavior of Web Forms, you have to resort to tricks or override methods. In ASP.NET MVC, you just change your programming style or simply replace the component.

ASP.NET Web Pages

ASP.NET Web Forms was relatively easy to embrace for developers and software professionals. ASP.NET MVC requires a bit of extra work and doesn’t really lend itself to being learned and discovered on a trial-and-error basis. So how high is the barrier to get into the world of ASP.NET?

ASP.NET Web Pages offers a new approach. ASP.NET Web Pages is not a framework aimed at professional developers, but still it is part of the ASP.NET platform and will be updated in the future. Let’s find out more.

Small, Simple, and Seamless

ASP.NET Web Pages targets an audience of Web developers who are involved in very simple projects either because they’re not software specialists or because the site to create is extremely simple indeed. This audience would benefit from even further simplicity such as a single page model and a simplified way of writing code and the view. ASP.NET Web Pages comes with a new IDE called WebMatrix and a simplified version of IIS, aptly named IIS Express. WebMatrix, in particular, wraps up server code, markup, and database tables in a new designer environment that makes it a snap to write pages and publish them to a site.

Code and View Together

With ASP.NET Web Pages, you write pages using a mixed syntax that incorporates both markup and code, but in a way that is a bit cleaner than today with either Web Forms or ASP.NET MVC code blocks. By using the @xxx syntax, where xxx is a built-in object, you can insert in the markup some dynamically calculated value and also use those components to emit ad hoc markup. Here’s an example:

<body>
   Today is @DateTime.Now
</body>

Such objects are more similar to ASP.NET MVC HTML helpers than to Web Forms controls, and they represent dynamic code you can interact with in a single environment while building the output you expect.

Note

The syntax supported by ASP.NET Web Pages (formerly codenamed Razor) is the new default language for defining views in ASP.NET MVC 3.

Summary

ASP.NET Web Forms is the Microsoft premier platform for Web applications. It was originally designed a decade ago to fit as closely as possible the skills and needs of the average developer of the time. Ten years ago, the typical developer was either a former C/C++/Java developer or an early adopter of HTML willing to do fancier things that JavaScript could just not support. In the middle, there was the Visual Basic developer, accustomed to RAD programming and slowly absorbing the basic concepts of object-oriented programming. ASP.NET Web Forms was designed for these developers. And it worked great for several years. Now, however, it is showing some clear signs of age.

The advent of AJAX revolutionized the perception of a Web application and sparked a paradigm shift—a long process that we have probably gone through for no more than 70 percent of its natural length. Web Forms is really close to its architectural end. If you lead a team of developers, and if your business is based on ASP.NET and Web applications, you should make sure that the framework of choice will take you just where you want and do it comfortably enough.

In the past years, the number of Web applications (including simple sites) has grown beyond imagination. As a developer, you might be asked to design and build anything from a simple site with just a small collection of data-driven pages up to the Web front end of an enterprise-class application, where scalability, extensibility, and customization are high on the priority list.

Is Web Forms up to the task? Sure it is, but you should consider that the conventional way of working of Web Forms doesn’t lend itself very well to creating testable code, mockable views, and layers. Web Forms is essentially UI focused and highly optimized for the RAD paradigm. I recommend that you seriously consider alternatives such as ASP.NET MVC or a new set of patterns and practices to make the most of the Web Forms framework.

To learn about ASP.NET MVC, I recommend an earlier book of mine, Programming Microsoft ASP.NET MVC (Microsoft Press, 2010). The rest of this book focuses instead on how to make the most of Web Forms today.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.168.46