Basic Web Programming Skills

The major differences between programming Web applications and Windows applications appear in the ch08_02 example, which you can see at work in Figure 8.5.

Figure 8.5. The ch08_02 application.

graphics/08fig05.jpg

We'll take a look at the various differences between Windows and Web applications in this example next .

Handling Events

When you click the See Message button in ch08_02, the message "No worries." appears in the text box, as you see in Figure 8.5. As we've seen, the code to handle a button click is identical to the code used in a Windows application, except that object names like TextBox1 begin with an initial capital letter by default:

 
 private void Button1_Click(object sender, System.EventArgs e) {  TextBox1.Text = "No worries.";  } 

However, there are huge differences behind the scenes. The most obvious difference is that ch08_02 appears in a Web browser while its code is handled on a remote Web server. Because Web server controls must work in a browser, they have fewer capabilities, and fewer properties and methods , than their Windows counterparts.

What's important to keep in mind is that each time you click a button, the entire Web form must be sent back to the server. In other words, if you're going to stick to C# code, you need a server round-trip every time something happens in the Web form. That introduces some complicationsamong other things, the Web server won't preserve the value of the variables across server round-trips unless we take some specific steps.

However, you don't need a server round-trip if you use a language that the browser understands, such as a scripting language like JavaScript. To use JavaScript, you use HTML client controls, not Web server controls. For example, to add an HTML button and text field (in HTML, text boxes are called text fields) to a Web form, click the HTML tab in the toolbox, and then add those controls to the form. HTML controls are not given names by default, so enter "Button1" for the button's (id) property in the properties window. Similarly, set the (id) property of the text field to "TextField1" . You can also give the button the caption "Show Message" by entering that text in the button's value property.

The next step is to add the JavaScript code. To do that, click the HTML button in the form designer so that you see the Web form's HTML. Next, select the button, Button1 , in the left drop-down list box above the code designer, and the onclick event (which is the HTML version of the C# Click event) in the right drop-down list. Doing so adds a new JavaScript event handler to the HTML for the button in our Web form's <HEAD> section like this:

 
 <HEAD>   .   .   . <!--  function Button1_onclick()   {   }  //--> </HEAD> 

When the button is clicked, the code in Button1_onclick will run. In JavaScript, you can refer to the text in the text field as document.Form1.TextField1.value . Therefore, to display the message "No worries." in the text field, you can use this JavaScript:

 
 function Button1_onclick() {  document.Form1.TextField1.value = "No worries."  } 

Moving Web Controls at Runtime

The second button in ch08_02 moves the text box when you click this button. But here too, things are different from how you'd code this in a Windows application. Web server controls don't have handy properties like Top or Right that let you position them at runtime. However, you can access properties like that as CSS style properties . Specifically, you can set the top and right location of a Web control by assigning values to the Style["Top"] and Style["Right"] properties, and the bottom and left locations with the Style["Bottom"] and Style["Left"] properties.

When you click the Move Text Box button, the code moves the text box down the page by assigning TextBox1.Style["Top"] the value 150px (that is, 150 pixels):

 
 private void Button2_Click(object sender, System.EventArgs e) {  TextBox1.Style["Top"] = "150px";  } 

You can see the result in Figure 8.6, where the text box has been moved downwards. Note that you must use grid layout for this to work, not flow layout. You can only position Web elements in an absolute way when you're using grid layout, or when you set the control's Style["Position"] property to "Absolute" .

Figure 8.6. Moving a text box at runtime.

graphics/08fig06.jpg

There are plenty of CSS styles available. You'll find the complete listing of CSS style properties like Top and Bottom at http://www.w3.org/TR/REC-CSS1 for CSS level 1 (called CSS1) and http://www.w3.org/TR/REC-CSS2/ for CSS level 2 (CSS2). These CSS specifications are maintained by the World Wide Web Consortium, W3C, a group responsible for standardizing HTML and XML. All of CSS1 and most of CSS2 is supported in Internet Explorer 6. If you want to learn about moving, coloring, and formatting your Web controls in a browser, these URLs are the place to do your research. For example, you can access the background color of a control like a text box this way: TextBox1.Style["Background-Color"] .

Posting Data Back to the Server

Take a look at the list box in ch08_02, Figure 8.6, which you see under the second button. When you add a list box to a Web form at design time, you can click the ellipsis button for its Items property in the properties window to open the ListItem Collection Editor that you see in Figure 8.7. Each item in a Web Server list box is a ListItem object, and you can configure those objects using that editor.

Figure 8.7. The ListItem Collection Editor.

graphics/08fig07.jpg

As with Windows forms, the default event for list boxes is SelectedIndexChanged , and we can display the item the user selected in the ch08_02 application's text box this way:

 
 private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) {  TextBox1.Text = "You selected " + ListBox1.SelectedItem;  } 

However, there's another difference here from Windows applications. If you run this application as we've created it and click a selection in the list box, nothing happens. The reason nothing happens is that the page wasn't sent back to the Web server.

Only the default event in a few controls, such as the Click event in buttons, automatically sends the page back to the server. Other events are stored and handled on the server when the whole page is sent back (as when a button is clicked). That's the standard way Web pages workyou make your selections and click a Submit button (which is what Web server buttons actually are) to send the page back to the server.

However, you can force all of a control's events, such as the list box's SelectedIndexChanged event, to be sent back to the Web server if you set the control's AutoPostBack property to true (the default is false ). When you set the list box's AutoPostBack property to true in the properties window and select an item in that list box at runtime, you'll see your selection in the text box, as you see in Figure 8.8.

Figure 8.8. Using the AutoPostBack property.

graphics/08fig08.jpg

Preserving a Web Application's Data Between Server Accesses

Another significant way in which Web applications differ from Windows applications is in saving the data in your application while the user works with that application. That's not an issue in Windows programming, because the program is running as the user works with it. But in a Web application, you're not directly connected to the server code. You're looking at a Web page in your browser on your own computer.

That means there are two places your application can store datain the client (the browser) and on the server. This is an important issue because the data in your application's code on the server is not preserved by default between round-trips. They're reset to their default value each time the page is sent on a round-trip to the server, so making sure that the data in your variables is preserved is up to you.

IMPLEMENTING AUTOPOSTBACK

In HTML, the AutoPostBack property is handled by a JavaScript function named doPostBack (so AutoPostBack won't work in non-JavaScript browsers).


For example, take a look at the Increment Counter button in the ch08_02 example. In Windows, you can program this button to use a variable named something like counter and increment it each time the button is clicked, displaying the new value in the text box:

 
 int counter = 0; private void Button3_Click(object sender, System.EventArgs e) {   counter++;   textBox1.Text = "Counter value: " + counter; } 

That's not going to work here, because each time you click this button, the entire Web page is sent back to the server, and the page's code is reloaded. This means all values like counter are initialized back to their initial values. Each time you click the button, you'd see "Counter value: 1" in the text box, no matter how many times you clicked the button. To fix that, you have to preserve the value of your data across server round-trips, and we'll take a look at two ways to do that.

Preserving Data in the Client

By default, the data in the controls in a Web form is stored in an HTML hidden field (an HTML <input> element with the type attribute set to "hidden") when the page is sent back to the server, so you don't have to worry about it. When the page is sent to the server and then back, that data is automatically restored in the controls. You can store your own data in that hidden control using the form's ViewState property. You store data with this property under a key as you would in a hash table; in this case, we'll use the key "counter" . When the user clicks the Increment Counter button, we'll retrieve the counter value, increment it, display it, and store it again:

 
 private void Button3_Click(object sender, System.EventArgs e) {  int counter = (int) this.ViewState["counter"];   counter++;   TextBox1.Text = "Counter value: " + counter;   this.ViewState["counter"] = counter;  } 

You still need to initialize counter to 0 the first time before trying to retrieve it from the ViewState property. You can do that in the Page_Load (not Form_Load ) event, which occurs when the Web page first loads. To make sure counter is initialized only once, you can use the Web form's IsPostBack property, which is true the first time the page loads, but false every time the page is posted back from the server:

 
 private void Page_Load(object sender, System.EventArgs e) {  if(!IsPostBack)   {   this.ViewState["counter"] = 0;   }  } 

Now whenever you click the Increment Counter button, the counter is correctly incremented, as you see in Figure 8.9.

Figure 8.9. Preserving data in the client.

graphics/08fig09.jpg

Preserving Data in the Server

You can also store data on the server using the ASP.NET Session object. When the user starts working with your Web application, a Session object is created for precisely the purpose we'll put it toto store local data. Note, however, that Session objects, maintained on the server, can time out after a period of no client accesses (usually 30 minutes, although you can alter a session's time out with its TimeOut property, which is set in minutes).

You can store and retrieve values using the Session object in C# code; here's how that might look when the user clicks the button to increment counter :

 
 private void Button3_Click(object sender, System.EventArgs e) {  int counter = (int) Session["counter"];   counter++;   TextBox1.Text = "Counter value: " + counter;   Session["counter"] = counter;  } 

Also we should initialize counter in the Page_Load event:

 
 private void Page_Load(object sender, System.EventArgs e) {  if(!IsPostBack)   {   Session["counter"] = 0;   }  } 

Detecting Browser Capabilities

There's another issue that you don't have to confront in Windows applicationsdetermining what browser the user has. Different browsers have different capabilities, which can make a big difference in the code you write if you are working with HTML directly. ASP.NET uses the Request object to handle the incoming data from the browser, and you can use it to learn about the user's browser. For example, to determine what kind of browser you're dealing withand therefore how you can work with ityou can use the Request object's Browser property. This property returns an object which itself has various properties that tell you about the browser the user has. You can see these properties in Table 8.1. Each property contains text (such as the browser's name ) or a Boolean value of true or false .

Table 8.1. Request.Browser Properties

TO DETERMINE

USE THIS

Browser name (example: IE)

Request.Browser.Browser

Browser type (example: IE6)

Request.Browser.Type

Is this a beta version?

Request.Browser.Beta

Is this an AOL browser?

Request.Browser.AOL

Is this Win16?

Request.Browser.Win16

Is this Win32?

Request.Browser.Win32

Major version (example: 6)

Request.Browser.MajorVersion

Minor version (example: 0)

Request.Browser.MinorVersion

Platform (example: WinNT)

Request.Browser.Platform

Supports ActiveX controls?

Request.Browser.ActiveXControls

Supports cookies?

Request.Browser.Cookies

Supports frames ?

Request.Browser.Frames

Supports Java applets?

Request.Browser.JavaApplets

Supports JavaScript?

Request.Browser.JavaScript

Supports tables?

Request.Browser.Tables

Supports VBScript?

Request.Browser.VBScript

Version (example: 6.0b)

Request.Browser.Version

For example, if you click the Get Browser button in our ch08_02 example, the code will display the name and version of the user's browser in the application's text box:

 
 private void Button4_Click(object sender, System.EventArgs e) {  TextBox1.Text = "Your browser is " + Request.Browser.Browser   + " " + Request.Browser.Version;  } 

You can see how this works in Figure 8.10.

Figure 8.10. Getting browser information.

graphics/08fig10.jpg

Besides the Request object, there's also a Response object. This object handles the data the server sends back to the browser. For example, to redirect users to another page, you can use the ASP.NET Response object's Redirect method. The Response object allows you to customize what you send back to the browser. For example, here's how the code might work in a Page_Load event handler if you wanted the user's browser to be immediately redirected to another page:

 
 private void Page_Load(object sender, System.EventArgs e) {  Response.Redirect("http://www.microsoft.com");  } 

The Response object is useful in other ways. For example, this object has a method, Write , that lets you write HTML directly to Web pages. To write an <h1> header with the text "No worries" in a Web form at runtime, you can use this C# code in the Page_Load event handler:

 
 private void Page_Load(object sender, System.EventArgs e) {  Response.Write("<h1>No worries</h1>");  } 

Adding Controls at Runtime

If you click the button labeled Add Button in ch08_02, a new button will appear, and when you click that new button, the text "You clicked the new button." will appear in the application's text box, as you see in Figure 8.11.

Figure 8.11. Adding a button at runtime.

graphics/08fig11.jpg

Adding Web controls to a Web form at runtime takes a little more work than in Windows forms. Controls based on the System.Web.UI.Control class support a Controls collection that holds the controls contained in the control. You can use the Add method of that collection to add new controls to a container control.

It's easiest to add new controls to a Web form by adding them to a container control, not to the Web form itself (to add controls directly to a Web form, you must add them to the Web form's <FORM> element, which is not easy to access directly). One popular container control is Panel (based on the HTML <div> element), and we'll add our new button to a Panel control, Panel1 , in the ch08_02 example. When the user clicks the button labeled Add Button, we create a new System.Web.UI.WebControls.Button object, set its caption to "Click Me!" , and add an event handler to it like this:

 
 System.Web.UI.WebControls.Button newButton; private void Button5_Click(object sender, System.EventArgs e) {  newButton = new System.Web.UI.WebControls.Button();   newButton.Text = "Click Me!";   Panel1.Controls.Add(newButton);   this.newButton.Click += new System.EventHandler(this.newButton_Click);  }  private void newButton_Click(object sender, System.EventArgs e)  {  TextBox1.Text = "You clicked the new button.";  } 

So far, so good. There's a problem here, however. The new button isn't actually stored in the data for the page, so every time the Web page gets sent back to the serverincluding when the new button itself is clickedthis new button will disappear. You can solve this problem by creating a new bool value named showButton that will keep track of whether the button has been created, and if so, will create the button again in the Page_Load event. Here's the code:

 
 System.Web.UI.WebControls.Button newButton;  bool showButton;  private void Button5_Click(object sender, System.EventArgs e) {   newButton = new System.Web.UI.WebControls.Button();   newButton.Text = "Click Me!";   Panel1.Controls.Add(newButton);   this.newButton.Click += new System.EventHandler(this.newButton_Click);  showButton = true;   this.ViewState["button"] = showButton;  } private void Page_Load(object sender, System.EventArgs e) {   if(!IsPostBack)   {     this.ViewState["counter"] = 0;  this.ViewState["button"] = false;  }  showButton = (bool) this.ViewState["button"];   if (showButton == true)   {   newButton = new System.Web.UI.WebControls.Button();   newButton.Text = "Click Me!";   Panel1.Controls.Add(newButton);   this.newButton.Click += new System.EventHandler(this.newButton_Click);   }  } 

That completes the overview of Web server applications and how they differ from Windows applications. Now it's time to start taking a closer look at the available Web server controls.



Microsoft Visual C#. NET 2003 Kick Start
Microsoft Visual C#.NET 2003 Kick Start
ISBN: 0672325470
EAN: 2147483647
Year: 2002
Pages: 181

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net