ASP.NET Web Forms C# Help

As mentioned earlier, much of the functionality in ASP.NET is achieved using Web Forms. Before long, you will dive in and create a simple Web Form to give you a starting point to explore this technology. First, however, this section reviews some key points pertinent to Web Form design. Note that some ASP.NET developers simply use a text editor such as Notepad to create files. We wouldn’t advocate this ourselves because the benefits you get via an IDE such as Visual Studio or Web Developer Express are substantial, but it’s worth mentioning because it is a possibility. H you do take this route, you have a great deal of flexibility as to which parts of a Web application you put where. This enables you, for example, to combine all of your code in one file. You can achieve this by enclosing code in <script> elements, using two attributes on the opening <script> tag:

<script language=”ct” runat=”server”>
// Setver-side code goes here.

The runet = ” server” attribute here is crucial because it instructs the ASP.NET engine to execute this code ~ the server rather than sending it to the client, thus giving you access to the rich environment hinted at earlier. You can place your functions, event handlers, and so on in server-side script blocks.

If you omit the runat = ” server” attribute, you are effectively providing client-side code, which will fail if it uses any of the server-side style coding that is discussed in this chapter. You can, however, use <script> elements to supply. client-side script in languages such as JavaScript For example.

<script language=”JavaScript” type=”text/JavaScript”>
// Client-side code goes here; you can also use “vbscript”.

Note that the type attribute here is optionaI, but necessary if you want XHTML compliance.

It may seem strange that the facility to add JavaScript code to your pages is included with ASP.NET. However, JavaScript allows you to add dynamic client-side behavior to your Web ‘pages and can be very useful, This is especially true for Ajax programming, as you will see in Chapter 39, “ASP.NET AJAX.”

It is possible to create ASP.NET files in Visual Studio, which is great for you, as you are already familiar with this environment for 01 programming. However, the default project setup for Web applications in this environment has a slightly more complex structure than a single. aspx file. This isn’t a problem for you, however, and does make things a bit more logical (more programmer-like and less Web developer like).
For this reason, you will use Visual Studio throughout this chapter for your ASP.NET programming  (instead of Notepad),’

The . aspx files can also include code in blocks enclosed by <% and %> and b tags. However, function definitions and variable declarations cannot go here. Instead, you can insert code that is executed as soon as the block is reached, which is useful when outputting simple HTML content. This behavior is similar to that of old-style ASP  ages, with one important difference: The code is compiled, not interpreted. This results in far better performance.

Now it’s time for an example. In Visual Studio, you create a new Web application by using the File > New > Web Site menu option. From the dialog box that appears, select the Visual C# language type and the ASP.NET Web Site template. At this point, you have a choice to make. Visual Studio can create Web . sites in a number of different locations:

  1. On your local IIS Web server
  2. On your local disk, configured to use the built-in Visual Web Developer Web server
  3. At any location accessible via FTP
  4. On a remote Web server that supports Front Page Server Extensions

The latter two choices use remote servers so you are left with the first two choices. in general, IIS is the best place to install ASP.NET Web sites because it is likely to be  closest to the configuration required when you deploy a Web site. The alternative, using the built-in Web server, is fine for testing but has certain limitations:

  1. Only the local computer can see the Web site.
  2. Access to services such as SMTP is restricted.
  3. The security model is different from IIS – the application runs in the context of the current user rather than in an ASP.NET-specific account..

This last point requires clarification because security is very important when it comes to accessing databases or anything else that requires authentication. By default, Web applications running on IIS do so in an account called ASP.NET on Windows XP, 2000, and Vista Web servers, or in an account called NETWORK SERVICES on Windows Server 2003. This is configurable if you are using IIS, but not if you use the built-in Web server .

For the purposes of illustration, however, and because you may not have IIS installed on your computer, you can use the built-in Web server. You aren’t worried about security at this stage, so you can go with simplicity.

 Create a new ASP.NET Web site called PCSWebAppl using the File System option, at C: \ ProCSharp Chapter 37, as shown in Figure 37-2.

Figure 37-2

Figure 37-2

After a few moments, Visual Studio .NET should have set up the following:

  1. PCSWebApp1, a new solution containing the CII Web application PCSWebApp1
  2. reserved folder called App_Data for containing data files, such as XMLfiles or database files
  3. Default. aspx, the first ASP.NET page in the Web application
  4. Default. aspx.cs, a “code-behind” class file for Default.aspx
  5. We. config, a configuration file for the Web application

You can see all of this in the Solution Explorer, as shown in Figure 37-3.

Figure 37-3

Figure 37-3

You can view.aspx files in design or source (HTML) view. This is the same as for Windows Forms (as discussed in Chapter 31, “Windows Forms”). The initial view in VisualStudio is either the design or source view for Default.aspx (you can toggle between the views or view them together in a split view using the buttons in the bottom left). The design view is shown in Figure 37-4.

Figure 37-4

Figure 37-4

Underneath the (currently empty) form, you can see where in the HTML for the form the cursor is currently positioned. Here the cursor is in a <div> element inside a <form> element inside the <body> element of the page. The <form> element is displayed as <formtform1> to identify the element by its id attribute, which you will see shortly. The <div> element is also labeled in the design view.

The source view for the page shows you the code generated inside the . aspx file:


If you know any HTML syntax, then this will look familiar to you. You are presented with the basic code required for an HTML page following the XHTML schema, with a few extra bits of code. The most important extra is the <form> element, which has an id attribute of form1. This element will contain your ASP.NET code. The most important thing to note here is the runat attribute. Just as with the server side code blocks you saw at the start of this section, this is set to server, meaning that the processing of the form will take place on the server. If you don’t include this reference, then no server-side processing will be performed, and the form won’t do anything. There can be only one server-side <form> element in an ASP.NET page.

The other interesting thing about this code is the <% Page %> b tag at the top. This tag defines page characteristics that are important to you as a C# Web application developer. There is a Language attribute that specifies that you will use C# throughout your page, as you saw earlier with <script> blocks. (The default for Web applications is Visual Basic .NET,although this can be changed using a Web.config file, which you will see later in this chapter.) The other three attributes- AutoEventWireup, CodeFile, and Inherits – are used to associate the Web Form with a class in a code-behind code file, in this case the partial class _Default in the file Default. aspx. cs. This leads straight into a necessary discussion about the ASP.NET code model.

The ASP.NET Code Model

In ASP.NET,a combination of layout (HTML) code, ASP.NET controls, and C# code is used to generate the HTML that users see. The layout and ASP.NET code are stored in an . aspx me, such as the one you looked at in the preceding section. The C# code that you add to customize the behavior of the form is contained either in the . aspx me or, as in the preceding example, in a separate, aspx.cs me, which is usually referred to as the “code-behind” file.

When an ASP.NET Web Form is processed – typically when a user requests the page, although sites can be pre compiled – several things happen:

  1. The ASP.NET process examines the page, and determines what objects must be created to instantiate the page object model.
  2. A base class for the page is dynamically created, including members for the controls on the page as well as event handlers for these controls (such as button click events).
  3. Additional code contained in the . asp~ page is combined with this base to complete the object model.
  4. The complete code is compiled and cached ready to process subsequent requests
  5. HTML is generated and returned to the user.

The code-behind me generated for you in the PCSWebAppl Website for Default aspx. is initially very sparse, First, you see the default set of namespace references that you are likely to use in ASP.NET Web pages:


Here, the Page_Load( ) event handler can be used to add any code that is required when the page is loaded, As you add more event handlers, and so on, this class file will become increasingly full of code. Note that you don’t see the code that wires up this event handler to the page – event handlers are inferred by the ASP.NET runtime, as noted earlier. This is due to the AutoEventWireUp attribute setting this to false will mean that you will need to associate the event handlers in your code with events on your own.

This class is a partial class definition because the process outlined earlier requires it. When the page is precompiled, a separate partial class definition is created from the ASP.NET code for your page. This includes all the controls you have added to the page. At design time, the compiler infers this partial class definition, which allows you to use IntelliSense in your code behind to reference controls on your page.

ASP.NET Server Controls

Your generated code doesn’t do very much yet, so next you need to add some content. You can do this in Visual Studio using the Web Form. designer; which supports drag-and-drop in just the same way as the Windows Forms designer.

You can add three typesof controls to your ASP.NET pages:


These controls don’t do anything more than the Web server controls, and the Web server controls provide a richer environment for developers more familiar with programming than with HTML design. If you learn how to use the Web server controls, then you will have all the information you require to use HTML server controls. For more information, check out Professional ASP.NET 2.0 (Wiley Publishing, lnc., ISBN 0-7645-7610-0).

Now you add a couple of Web server controls to the PCSWebAppl Web site you created in the last section. All Web server controls are used in the following XMLelement-type form:

<asp:controlName runat=’server’ attribute=’value”>Contents</asp:controlName>

In the preceding code, control Name is the name of the ASP.NET server control, at tribute= ‘value’ is one or more attribute specifications, and Contents specifies the control content, if any. Some controls allow properties to be set using attributes and control element content, such as Label (used for simple text display), where Text can be specified in either way. Other controls might use an element containment scheme to define their hierarchy ~ for example Table (which defines a table), which can contain Table Row elements in order to specify table rows declaratively.

Because the-syntax for controls is based on XML(although the controls may be used embedded in non-XML code such as HTML), it is an error to omit the closing tags and /> for empty elements, or to overlap controls.

Finally, you once again see the runat=” server ~attribute on the Web server controls. It is just as . essential here as it is elsewhere, and it is a.common mistake to skip this attribute. If you do, your Web Forms won’t work.

This first example is simple. Change the HTML design view for Default.aspx as follows:


Here you have added two Web Form controls: a label and a button.

Note that as you do this, Visual Studio .NET IntelliSense predicts your code entry, just as in the C# code editor. Also, if you edit your code in split view and synchronize the views, the element that you are , editing in the source pane will be highlighted in the design pane.

Going back to the design screen, you can see that your controls have been added, and named using their ID attributes (the ID attribute is often known as the identifier of a control). As with Windows Forms, you have full access to properties, events, and so on through the Properties window and get instant feedback in code or design whenever you make changes. .

You can also use the CSS Properties window and other style windows to style your controls. However, unless you are familiar with CSS, you will probably want to leave this technique alone for now and concentrate on the functionality of the controls.

Any server controls you add will automatically become part of the object model for the form that you are building. This is an instant bonus for Windows Forms developers – the similarities are beginning to emerge!

 To make this application do something, you can add an event handler for clicking the button. Here you can either enter a method name in the Properties window for the button or just double-click the button to get the default event handler. H you double-click the button, you will automatically add an event handling method as follows: .


Here, the onclick attribute lets the ASP.NET runtime know to wire up the click event of the button to the trigger But ton_Click() method when it generates the code model for the form.

Modify the code in trigger Button_Click() as follows (note that the label control type is inferred from the ASP.NET code so that you can use it directly from the code behind):

Now you’re ready to make it go. There is no need to build the project; you simply need to make sure everything is saved and then point a Web browser at the location of the Web site. If you had used lIS, this would be simple because you would know the URL to point at. However, because you are using the built-in Web server for this example, you need to start things running. The quickest way to do this is to press Ctrl+F5, which will start the server and open a browser pointing at the required URI


When the built-in Web.server is running, an icon will appear in your system tray. By double-clicking this icon, you can see what the Web server is doing, and stop it if required (see Figure 37-5).

In Figure 37-5, you can see the port that the Web server is running on and the URL required to see the Web site you have created.

Figure 37-5

Figure 37-5

The browser that has opened should display the Click Me button on a Web page. Before you press the button, take a quick look at the code received by the browser by selecting Page ¢ View Source (in IE7). The <form> section should look something like this:


The Web server controls have generated straight HTML: <span> and <input> for <asp: Label> and <asp: Button>, respectively. There is also an <input type= ‘hidden”> field with the name VIEW STATE.This encapsulates the state of the form, as mentioned earlier. This information is used when the form is posted back to the server to re-create the user interface, so that the server can keep track of changes and so on. Note that the <form> element has been configured for this; it will post data back to Default.aspx (specified in action) via an HTTP POST operation (specified in method). It has also been assigned the name form1.

After clicking the button and seeing the text appear, check out the source HTML again (spacing has been added for clarity):


This time, the value of the view state contains more information because the HTML result relies on more than the default output from the ASP.NET page. In complex forms this cart be a very long string indeed, but you shouldn’t complain because so much is done for you behind the scenes. You can almost forget about state management, keeping field values between posts, and so on. Where the length of the
view state string becomes a problem, you can disable the view state for controls that do not need to retain state information. You can also do this for entire pages if you want, which can be useful if the page does not ever need to retain state between post backs to improve performance.

For more on view state, see Chapter 38, “ASP.NET Development.”

To convince yourself that you don’t need to perform any compilation manually, try changing the text “Button clicked!” in Default.aspx. cs to something else, saving the file, and clicking the button again. The text on the Web page should change appropriately.

The Control Palette

This section takes a quick look at some of the available controls before you put more of them together into a full, and more interesting, application. Figure 37-6 shows the toolbox that you see when editing ASP.NET pages.

Figure 37-6

Figure 37-6

Note that the following control descriptions discuss properties – in all cases, the corresponding attribute for use in ASP.NET code is identically named. This section isn’t an attempt to provide a complete reference, so instead, we will focus on only the most frequently used controls and properties. The controls you will see in this chapter are in the Standard, Data, and Validation categories. The Navigation and Login and Web Parts categories are covered in Chapter 38, “ASP.NET Development,” and the AJAX Extensions controls in Chapter 39, “ASP.NET AJAX.” The Reporting controls to be presented on Web pages, which enable reporting information, including Crystal Reports, are not covered in this book.

Standard Web Server Controls

Almost all the Web server controls (in this and other “Categories)inherit from System. Web.UI .WebControls .WebControl,.which in turn inherits from Sys tern. Web.UI . Control. Those that don’t use this inheritance instead derive either directly from Control or-from a more specialized base class that derives (eventually) from Control. As a result, the Web server controls have many common properties and events that you can use as required. There are quite a few of these, so we won’t attempt to cover them all, just as with the properties and events of the Web server controls themselves.

Many of the frequently used inherited properties are those that deal with display style. This can be controlled simply, using properties such as ForeColor, BackColor, Font, and so on, but can also be controlled using cascading style sheet CSS)classes. To use CSS styling you set the string property Css Class to the name of a C55 class in a separate file. You can use the C5S Properties window along with the style management windows to assist you with C55 control styling. Other notable properties
include Width and Height to size a control, AccessKey and TabIndex to ease user interaction, and Enabled to set whether the control’s functionality is activated in the Web Form.

Some control can contain other controls, building up a control hierarchy on a page. You can get access to the controls contained by a given control using its Controls property, or to the container of a control via the Parent property.

You are likely to use the inherited Load event most often, to perform initialization on a control, and PreRender to perform last-minute modifications before HTML is output by the control.

Plenty more events and properties exist, and you will see many of these in more detail in the next chapter. In particular, the next chapter deals with more advanced styling and skinning techniques. The following table describes the standard Web server controls in more detail.




Data Web Server Controls

The data Web server controls are divided into two types:

  1. Data source controls (SqlDataSource, AccessDataSource, LinqDataSource,
  2. Data display controls (GridView, DataList, DetailsView, FormView, ListView, Repeater, and DataPager)

In general, you will place one of the (nonvisual) data source controls on a page to link to a data source; then you will add a data display control that binds to a data source control to display that data. Some of the more advanced data display controls, such as GridView, also allow you to edit data.

All the data source controls derive from either System. Web.UI . DataSource or  System. Web.UI . HierarchicalDataSource. These classes expose methods such as GetView() (or GetHierarchical view ()) to give access to internal data views and skinning capabilities.

The following table describes the various data source controls. Note that there is less detail about properties in this section than in others – mainly because configuration of these controls is best done graphically or through wizards. Later in this chapter, you will see some of these controls in action.


Next, you have the data display controls, shown in the following table. Several of these are available to suit various needs. Some are more fully functional than others, but often you can go with simplicity (for example, when you don’t need to be able to edit data items).


Validation Web Server Controls

Validation controls provide a method of validating user input without (in most cases) your having to write any code at all. Whenever postback is initiated, each validation control checks the control it is validating and changes its Is valid property accordingly. If this property is false, then the user input from the validated control has failed validation. The page containing all the controls also has an Is Valid property – if any of the validation controls has its version of this property set to false, then this will be false also. You can check this property from your server-side code and act on it.

Validation controls also have another function. Not only do they validate controls at runtime; they can also output helpful hints to users. Simply setting the Error Message property to the text you want means users will see it when they attempt to postback invalid data.

The text stored in Error Message may be output at the point where the validation control is located, or at a separate point, along with the messages from all other validation controls on a page. This latter behavior is achieved using the Validation Summary control, which displays all error  messages along  with additional text as required.

All validation controls inherit from Base Validator and thus share several important properties. Perhaps the most important is the Error Message property discussed earlier, with the Control To  Validate property coming in a close second, This property specifies the programmatic 1D of the control that is being validated. Another important property is Display, which determines whether to place text at the validation summary position (if set to none), or at the validator position, You also have the choice to make space for the error message even when it is not being displayed.(set
Display to Static) or to dynamically allocate space when required, which might shift page contents around slightly (set Display to Dynamic). The following table describes the validation controls,


In this example, you create the framework for a Web application, a meeting room booking tool. (As with the other examples in this book, you can download the sample application and code from the Csharp Web site at At first, you will include only the front end and simple event processing; later, you will extend this example with ADO.NET and data binding to include server-side business logic.

The Web Form you are going to create contains fields for user name, event name, meeting room, and attendees, along with a calendar to select a date (you are amusing for the purposes of this example that you are dealing with all-day events). You will include validation controls for all fields except the calendar, which you will validate on the server side, and provide a default date in case none has been entered.

For user interface (UI) testing, you will also have a Label control on the form that you can use to display submission results.


After the title of the page (which is enclosed in HTML <hl> tags to get large, title-style text), the main body of the form is enclosed in an HTML <table>. You could use a Web server control table, but this introduces unnecessary complexity because you are using a table purely for formatting the display, not to be a dynamic UI element. This is an important point to bear in mind when designing Web Forms – don’t add Web server controls unnecessarily. The table is divided into three columns: the first column holds simple-text labels; the second column holds UI fields corresponding to the text labels (along with validation controls for these); and the third column contains a calendar control for date selection, which spans four rows. The fifth row contains a submission button spanning all columns, and the sixth row contains a Validation Summary control to display error messages, when required (all the other validation controls have Display= “None”, because they will use this summary for display). Beneath the table is a simple label that you can use to display results for now, before you add database access later:



Most of the ASP.NET code in this file is remarkably simple, and much can be learned simply by reading through it Of particular note in this code is the way in which list items are attached to the controls for selecting a meeting room and multiple attendees for the event:


Here you are associating List Item objects with the two Web server controls. These objects are not Web server controls in their own right (they simply inherit from System. Object), which is why you don’t need to use Runat=” server’ on them. When the page is processed, the <asp: List  ltem> entries are used to create List ltem objects,which are added to the Items collection of their parent list control.This makes it easier for you to initialize lists than to write code for this yourself (you would need to create a List Item Collection object,add List Item objects,and then pass the collection to the list control). Of course, you can still do all of this programmatically if you want.


In design view, the form you have created looks like Figure 37-7. This is a fully functioning UI, which maintains its own state between server requests, and validates user input. Considering the brevity of the preceding code, this is quite something. In fact, it leaves you with very little to do, at least for this example; you just need to specify the button click event for the submission button.

Actually, that’s not quite true. So far, you have no validation for the calendar control. All you need to do is give it an initial value. You can do this in the Page_Load() event handler for your page in the code behind file:


Here you just select today’s date as a starting point. Note that you first check to see if Page_Load() is being called as the result of a postback operation, by checking the Is postBack property of the page. If a postback is in progress, this property will be true and you leave the selected date alone (you don’t want to lose the user’s selection, after all).


Figure 37-7

Figure 37-7

Here you just set the result Label control Text property to a result string,which will then appear below the main table.In IE, the result of such a submission might look something like Figure 37-8, unless there are errors, in which case the Validation Summary will activate instead, as shown in Figure 37-9.

Figure 37-8

Figure 37-8

Figure 37-9

Figure 37-9

Posted on November 2, 2015 in ASP.NET Pages, Uncategorized

Share the Story

Back to Top