This section uses the in-practice approach that we’ll use in the rest of the book. We’ll analyze every aspect of a topic using a problem-solution-discussion style. The first topic we’ll discuss in this way is how to handle PostBack in a Web Form. Because the founda- tion of ASP.NET is the same for all versions, we’ve designed this scenario to help you understand a common challenge that you can solve using any version of ASP.NET.
Handling PostBack
HTML forms consist of a series of input tags used to capture values when they’re sub- mitted. ASP.NET uses PostBack to implement a mechanism that lets the developer han- dle this behavior easily. Mastering PostBack is important because the ASP.NET model is based on this concept.
PROBLEM
As a user, you want to interact with the page in the easiest way possible. If you need to correct a value, it’s easier to find it than to do some rewriting.
SOLUTION
The first time you request a page, ASP.NET renders its content and generates the cor- rect markup. Let’s suppose we have a page with a Button; this Button will be the con- trol that causes a PostBack when it’s clicked. A second request for the page is caused by the PostBack and is executed differently by ASP.NET. Every control on the page has TECHNIQUE 1
21 TECHNIQUE 1 Handling PostBack
Let’s imagine you have a basic form with two TextBox controls that capture first name and last name and a DropDownList in which the user selects his country from a limited set of values. The code for this form is shown in the following listing.
<html>
...
<form runat="server">
Your first name:
<asp:textbox runat="server" ID="FirstName" />
<br />
Your last name:
<asp:textbox runat="server" ID="LastName" />
<br />
Your country:
<asp:DropDownList runat="server" id="Country">
<asp:ListItem value="IT">Italy</asp:ListItem>
<asp:ListItem value="UK">UK</asp:ListItem>
<asp:ListItem value="USA">USA</asp:ListItem>
</asp:DropDownList>
<br />
<asp:button runat="server" Text="Next" ID="ClickButton"
OnClick="HandleSubmit" />
</form>
</html>
Try to run this example and submit the form. Even though you have no code in place to handle the state logic, the page will be posted back to server and a response will be generated. You can see the results in figure 1.8.
What’s interesting about this exam- ple is that we didn’t specifically handle state maintenance across different requests. Automatically handling state is one of the services that a framework such as ASP.NET offers to you at no cost.
Now that you know the basics, let’s improve the code.
Using container controls
You can use container controls to group controls together. Building on listing 1.1, let’s add a simple container control and include the previous controls inside it, as shown in the following listing.
Listing 1.1 Handling PostBack with the Web Form model
Figure 1.8 Web Form behavior resulting from the code shown in listing 1.1. After PostBack, the input boxes retain their values and new text that reflects the input is added at the top of the form.
22 CHAPTER 1 Getting acquainted with ASP.NET 4.0
Markup:
<html>
...
<form runat="server">
<asp:Placeholder id="FormContainer" runat="server">
Your first name:
<asp:textbox runat="server" ID="FirstName" />
<br />
</asp:Placeholder>
<asp:Placeholder id="FormResponse" runat="server"
Visible="false">
<asp:Literal id="ResponseText" runat="server" />
</asp:Placeholder>
</form>
...
</html>
C#:
void HandleSubmit(Object sender, EventArgs e) {
FormContainer.Visible = false;
FormResponse.Visible = true;
ResponseText.Text = string.Format("Hello {0} {1} from {2}", FirstName.Text,
LastName.Text,
Country.SelectedItem.Text);
} VB:
Sub HandleSubmit(sender as Object, e as EventArgs)
FormContainer.Visible = False
FormResponse.Visible = True ResponseText.Text = string.Format("Hello {0} {1} from {2}",
FirstName.Text, LastName.Text,
Country.SelectedItem.Text) End Sub
We used two Placeholder controls to isolate data input and to show results. This sim- ple control can include other controls, so it’s useful when you need to group controls.
For example, you could use the Visible property to tweak the visibility of some con- trols. This property is fundamental; it instructs the Page Parser to not produce the control content when it renders the Web Form.
NOTE If you need to determine at runtime whether a page is in PostBack state or not, you can check the IsPostBack property of the Page class.
IsPostBack is a boolean property whose value is True if the page is in Post- Back state. It’s often used to avoid loading data from a database after a Post- Back, using the ViewState as storage.
Listing 1.2 A complete Web Form with markup and code
Form container becomes invisible
Response text container
is shown
23 TECHNIQUE 2 Form validation
The technique shown in listing 1.2 is the preferred way to make a Web Form. You can have both data entry and response feedback in the same page, and show or hide blocks based on the state. In this example, we applied one of the most common patterns in ASP.NET applications. Both the first and the second requests are shown in figure 1.9.
DISCUSSION
PostBack is fundamental in ASP.NET applications based on Web Forms. Working with PostBack helps you to understand the magic behind this model. Like it or not, Web Forms boost productivity. If you’re an experienced web developer, PostBack might seem restrictive. In reality, this model is flexible enough to let you add your own touch and implement your needs.
Now that you’re ready to use the Web Form paradigm, it’s time to move on and gain more control over ASP.NET infrastructure by using form validation. Form valida- tion is one of the best examples of how to increase productivity with little effort. In common forms, you need some control over the user to ensure that she’s inserting the right values into your form. That’s when the ASP.NET validation infrastructure comes to the rescue.
Form validation
By validating data on a form, you can guide your user to enter the correct values and, at the same time, enforce your application needs. Validation is a useful tool, especially when you use it at both client and server side.
To fully appreciate the content of this section, you should be familiar with the con- cepts presented in technique 1.
PROBLEM
Form validation is just another pain that web developers need to address. The average user isn’t happy when he has to re-enter data into a form from scratch because he for- got to include a seemingly trivial piece of data, like a ZIP code. When the user makes a mistake and has to re-enter something, he expects to see the data he already entered on the form. This expectation probably derives from the classic Windows application, where, obviously, you have true state support.
Figure 1.9 The Web Form we created in listing 1.2, before and after PostBack.
The first request contains the controls to add your input. The second request hides them and shows only the resulting text.
TECHNIQUE 2