BIT 285: ( Web) Application Programming Lecture 04: Thursday, January 15, 2015 Standard Server...

51
BIT 285: (Web) Application Programming Lecture 04: Thursday, January 15, 2015 Standard Server Controls (Continued), Page Object, View State, PostBack, IsPostBack, Connecting to a Database Instructor: Craig Duckett

Transcript of BIT 285: ( Web) Application Programming Lecture 04: Thursday, January 15, 2015 Standard Server...

BIT 285: (Web) Application Programming

Lecture 04: Thursday, January 15, 2015

Standard Server Controls (Continued), Page Object, View State, PostBack, IsPostBack,

Connecting to a Database

Instructor: Craig Duckett

2

JUST A HEAD'S UP: Assignment 1: Web Forms is due Tuesday, February 3, (zipped and uploaded to StudentTracker by midnight)

3

Standard Server Controls (Continued)

4

Check Boxes and Radio Buttons

Common Check Box and Radio Button Attributes

5

Check BoxesI can drag-and-drop some check boxes and radio buttons to a web form from the Toolbox, and immediately after positioning them the way I would like and perhaps renaming all the controls and giving them meaningful text to display, when I run the program the checkboxes seem to work as expected—you can select and deselect the checkboxes as expected. I said "seem" above because at this point the checkboxes are not associated with event handlers of any kind, so they merely appear as if they are doing something important but are not.

6

Radio ButtonsWhile your check boxes appear to work correctly—you can select and deselect each one as you'd expect—the radio buttons reveal a different case. You can select all three of the radio buttons, but you are unable to deselect them. This is because radio buttons are meant to belong to a group, and we did not group the radio buttons when we dragged-and-dropped them to the web form.

7

Radio ButtonsIn Design view, hold down the Ctrl key and click on each of the three radio button controls, then in the Properties panel scroll to GroupName and give it at name. Return to Source view to see that all the radio buttons have now been added to the same group.

You could have added a GroupName for each individual radio button one at a time, but the Ctrl key trick speeds things up considerably. You could have also added the GroupName for each radio button directly in the code.

When you run your program again, you'll see your radio buttons now work as expected.

8

Radio ButtonsIf you want, you can pre-select a radio button by default by changing its Checked property to true, either by doing this in the Properties panel or adding it directly into the radio button's code.

NOTE: You can do the same thing with check boxes.

9

CheckBoxList and RadioButtonList ControlThe CheckBoxList and RadioButtonList controls allow you to group check boxes and radio buttons in the same way as you might create a DropDownList control (which we will discuss a bit later). In most cases, using the RadioButtonList control is preferable—and easier—to using the RadioButton control as it automatically assigns the radio buttons to the same group

10

Check Boxes and Radio Button Event HandlersAdding event handlers to check boxes and radio buttons are just as easy as when we added them to out buttons and labels in the previous class and in-class exercise. We just have to make sure to change the AutoPostBack behavior to True in the Properties panel in Design view for every control we want to associate an event with.

11

Drop-Down Lists and List Boxes

Common Attributes of List Box Controls

Common Attributes of List Items

12

Drop-Down Lists and List BoxesCommon Properties of List Controls

A Common Event of All List Controls

13

Drop Down List and List Boxxx

14

Other Standard Server ControlsThere are several other Standard server controls that you will need to familiarize yourself with, including Image and Hyperlink controls, the File Upload control, the Command event, as well as additional features of the Button, Label, and Text Box controls. Due to time restrictions—as well as for the sake of brevity—we will not be examining these controls in class, so you will have to read up and experiment with them on your own using the Murach book and/or the Essential Skills material from the Help Guides. Please Note: it will be assumed that you will know how to use these other controls in future ICEs as well as for the Assignments, so please do not neglect doing the required "outside class" work that is necessary for learning how these controls operate, their unique settings, and use of their event handlers.

Murach

• Labels and Text Boxes: Pages 198-200

• Image and Hyperlink: Pages 202-203

• File Upload: Pages 204-205

• Buttons, Link Buttons, Image Buttons: Pages 206-207

• Command Event: Pages 208-209

• Bullet Lists: Pages 216-217

Essential Skills

• Button: Lesson 4-2

• Labels and Literal: Lesson 4-3

• Text Box: Lesson 4-4

15

The Page Object

16

A Very Brief Look at the Page Object

NOTE: I wanted to mention the Page object here briefly in order to "set the stage" for the content to follow. I will be going over the Page object in much more detail in Lecture 6.

In a web application, events can occur at three levels1. At the Application Level, e.g., Application Start (Lecture 6)2. At the Page Level, e.g., Page Load (Lecture 6)3. At the Control Level, e.g., Button Click

ViewState variables are used to preserve data across page postback (today's lecture)By default, ViewState of one webform is not available in another webform (today's lecture)

Techniques to send data from one webform to another4. Query Strings (Lecture 5)5. Cookies (Lecture 5)6. Session State (Lecture 6)7. Application State (Lecture)

17

A Look at the Page Object

Web applications work on a stateless protocol. Every time a request is made for a webform, the following sequence of events occur:

1. Web Application creates an instance of the requested webform.

2. Processes the events of the webform.

3. Generates the HTML, and sends the HTML back to the requested client.

4. The webform gets destroyed and removed from the memory.

18

A Look at the Page Object

When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.

The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing in a later lecture.

The page life cycle phases are:

• Initialization

• Instantiation of the controls on the page

• Restoration and maintenance of the state

• Execution of the event handler codes

• Page rendering

19

Suggested Page Links of Interest

• The Page Object (W3Schools)

• Understanding Page Properties (Peachpit Press)

• The ASP.NET Page Object Model (Microsoft)

• ASP.NET Application and Page Life Cycle (Code Project)

• ASP.NET Page Life Cycle (TutorialsPoint)

20

A Look at View State

21

A Look at View State

The web is stateless. It means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, it cannot hold the client information on a page. As for example , if we enter a text on a client machine and hit the submit button, text does not appear after the post back , because the page is recreated anew on its round trip (just as demonstrated in this 'classic' ASP example).

22

A Look at View StateWhen a form was submitted in earlier or "classic" versions of ASP, all form values were cleared once submitted. Suppose you submitted a form with a lot of information and the server comes back with an error. Now you have to go back to the form and correct the information, but when you click the browser's back button, guess what happens? ALL the form values have been cleared, and now you have to start filling out the form all over again! I remember this happening quite a bit in the so-called "Golden Age" of the World Wide Web, because a great many sites did not maintain ViewState.

When a form is submitted in ASP.NET, the form reappears in the browser window together with all form values. How come? This is because ASP.NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server. That status is defined through a hidden field placed on each html page with a <form runat="server"> control.

The source code might look something like this:

<form name="groovyForm" method="post" action="groovyPage.aspx" id="groovy1"><input type="hidden" name="__VIEWSTATE" value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" /> <!-- some groovy code --></form>

23

A Look at View State

Maintaining the ViewState is now the default setting for ASP.NET Web Forms. If you do NOT want to maintain the ViewState, include the directive <%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute EnableViewState="false" to any control.

Let's look at an .aspx example that demonstrates the "old" way of doing things. When you click on the Click Me button, the intention is for the displayed number to increment by 1, but that is not the case.

24

With this code in place, when we run the application, and click the Click Me button, we expect the count to be increased every time the button is pressed. When we click it the first time, it gets incremented to 1, but after that, no matter how many times we click it, the value stays at 1. This is because of the stateless nature of the web applications that work on HTTP protocol.

25

A Look at View State

What happens when we click the Button?

When we click the Button, the Default.aspx web form gets posted to the server. This is a PostBack request, not a GET request. So, when the web form is posted back, a new instance of this web form is created again, initializing the ClicksCount variable to zero. This time, the code that is wrapped between if(!IsPostBack) block is not executed. Button1_Click() event gets executed as this is a PostBack event. ClicksCount is incremented from 0 to 1. The value is then assigned to the Text Property of TextBox1. The server generates the HTML, sends it to client, and then destroys the web form.

At this Point, we should see the value increased to 1. And we do.

So what happens when we click the Button on the web form again?

When we click the button for the second time, the web form gets posted back again. A new instance of the web form is created. ClicksCount is initialized to zero. In the Button1_Click() event, the value gets incremented to 1 and assigned to TextBox1. The server generates the HTML, sends it to client, and then destroys the web form.

So, no matter how many times you click the Button, the value of the TextBox, will not move beyond 1.

26

A Look at View StateNow, let's see how to preserve the state between requests using ViewState variables. I'll rewrite the "code behind" code for a duplicate Default2.aspx web form as shown to the right.

Now when we click the button the value gets incremented every time we click. So how is this possible now? It's possible because, we are using the ViewState variable named Clicks (we might have named this anything, even "Winkus") to preserve the data between requests. The ViewState data travels with every request and response between the client and the web server.

27

A Look at View State

Now, let's try to achieve the same behavior, without explicitly storing data in a ViewState variable. I'll create a duplicate Default3.aspx web form, and modify the 'code behind' code as demonstrated on the right.

Upon clicking the button, the value gets incremented correctly as expected. This is possible because, TextBox1 is an ASP.NET server control, that uses ViewState internally, to preserve data across postbacks.

28

A Look at View StateBecause web forms have very short lifetimes, ASP.NET takes special steps to preserve the data entered in the controls on a web form.

Data entered in controls is sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load(), Button_Click(), and many more events, that occur after Page_Init() event. We will discuss the events in the life cycle of a web form and the order in which they occur in later lectures.

On the other hand the HTML controls, do not retain state across post backs. Only ASP.NET server controls retains state. To prove this

1. Add a new web form to the web site project2. Drag and Drop Input(Text) control from the HTML tab, in the ToolBox3. Drag and Drop TextBox control from the Standard tab, in the ToolBox4. Finally drag and drop a button5. Set the newly added web form as the start page by right clicking on it, in the solution explorer6. Run the project, by pressing CTRL + F57. Type "TEST" into both the controls (ASP.NET TextBox and the HTML TextBox), and press the button8. You should see that, the value in the ASP.NET TextBox is preserved across postback, but not the value in the

standard HTML textbox.

29

A Look at View State

AN INTERESTING NOTE:

An HTML control can be converted to an ASP.NET server control simply by adding the runat="server" attribute in the HTML source as shown below.

<input id="Text1" runat = "server" type="text" />

Now, if you type TEST and click the button, both controls retain state across postback

ViewState data is serialized into base64-encoded strings, and is stored in Hidden input field __ViewState. To view this hidden input field, right click on the web page when it is in the browser to view the source code.

We will look at ViewState again when we "officially" talk about Session States and Application variables in another week or so.

31

A Look at PostBack

A PostBack is any request for a page that is not the first request. A PostBack will always be in response to a user action (triggered most commonly by a Button, AutoPostBack control, Ajax, etc)

32

A Look at PostBack

The ASP.NET paradigm works on the fact that the web server and web clients are entirely disconnected one from another. Communication between them is, generally speaking, via an HTTP Request and an HTTP Response. The client sends a request to the server and the server responds with a stream of HTML markup back down to the client.

When you first go to a web page, it is served back to you "clean", for want of a better description. There may be a QueryString or there may be a Form object which the server processes to decide what data to serve back to the client, but that's pretty much it.

With ASP.NET, we have the concept of a PostBack. That means that, in response to a client-side event (e.g., a button click, etc) the page is requested a second time. Behind the scenes a submit action has been initiated on the page's Form object. Two hidden elements of the page's Form collection tell the server which web control has initiated this "Post-Back-to-the-Server" and which server-side event to process. Broadly speaking, that tells the server which server-side code to run.

PostBack is really not much more than a form submission which the server is able to interpret. However, through the IsPostback property of the Page object, ASP.NET is able to tell whether the page is being requested for the first time, or as the result of a PostBack. This allows the developer to control which code runs in either scenario.

33

The Processing Cycle for an ASP.NET Web Form

These steps will continue as long as the user continues to work on this page. Each cycle in which information is displayed then posted back to the server is sometimes also called a round trip.

1. The user requests an ASP.NET web form. In this example, the request uses the HTTP GET method.

2. On the server, the page is run, doing any preliminary processing such as compilation (if necessary), as well as calling other handlers as part of the page and application lifecycle (covered later in the chapter).

3. The Page_Load method of the page is called.4. The rest of the page executes, which ultimately results in a generated HTML response

which is sent back to the browser. Part of this generated HTML is the view state (discussed below) information contained within a hidden HTML input element. As well, the action and method attributes of the element are set so that the page will make a post back request to the same page when the user clicks the Enter button.

5. Browser displays the HTML response.6. The user fills in the form then causes the form to post back to itself (perhaps by clicking

a button). If the user clicks a link that requests a different page, then the following steps are not performed, since with the new page request, we would return back to step one.

7. The page is posted back to the server, usually using the HTTP POST method. Any form values along with the view state information is sent along as HTTP form variables.

8. On the server, the page is run (no compilation will be necessary since it will have already been compiled). The ASP.NET run-time recognizes that this page is being posted back due to the view state information. All user input is available for programmatic processing.

9. The Page_Load method is called.10. Any invoked control event handlers are called. In this case, a click event handler for the

button will be called.11. The generated HTML is sent back to the browser.12. Browser displays the HTML response.

35

A Look at IsPostBack

36

A Look at IsPostBackIsPostBack is a property of an ASP.NET web form that tells whether or not the page is on its initial load or if a user has perform some action on the page (like clicking a button) that has caused the page to post back to itself. The value of the IsPostBack property will be set to true when the page is executing after a postback, and false otherwise. We can check the value of this property based on the value and we can populate the controls on the page accordingly.

IsPostback is normally used in a Page_Load() event to detect if the web page is being generated due to a postback requested by an event on the page or if the page is being loaded for the first time. The typical way developers use IsPostBack is by employing it with the negation operator ! as demonstrated in the snippet of code on the right.

38

Data Exploration

39

Connecting to a Database

To connect to a database and work with its data, you can use an ASP.NET control called a data source. To illustrate how this works, the following topics show you how to work with a data source control called SqlDataSource. This control can be used to retrieve data from an SQL database file, such as a Microsoft SQL Server database file.

40

WALK THROUGH: Connecting to a Database

1. Create a new ASP.NET Empty Web Site called lec4demo2

2. Right-click on the project in the Solution Explorer and add a new Folder named App_Data

3. Download the lec4demo2.zip file and extract the lec4demo2.mdf file to your desktop (or other location of your choosing)

4. Right-click on the App_Data folder, then Add an Existing Item by browsing to and selecting the lec4demo2.mdf file.

5. Double-click on the lec4demo2.mdf file in the Solution Explorer to open the Server Explorer column with lec4demo2.mdf showing up under Data Connections with its folders broken out by Tables, Views, Stored Procedures, and so on.

6. Open the Tables folder, to reveal the Customer and Invoice tables.

7. Click on the Customer table to display its fields (CustomerID, Customer Name) and Data Types.

41

WALK THROUGH: Connecting to a Database

8. Right-click on the Customer table and select Show Table Data to display the table data.

9. Do the same for the Invoice table, the close all the database windows in Visual Studio.

10. Right-click on the project in Solution Explorer and add a new Web Form, keeping the default Defalut.aspx name.

11. Click on the lec4demo2.mdf database in the Server Explorer to give it the focus, then click on the Connect to Database icon from the toolbar to bring up the Add Connection window.

CONTINUED NEXT SLIDE

42

WALK THROUGH: Connecting to a Database12. Depending on which type of database file you have, click the Change button and select a Data Source type that matches

your database file, which usually depends on the file extension, then browse to the database file to select. Test your connection with the Test Connection button.

• MDB or ACCDB – Microsoft Access Database File (OLE DB)• SDF – Microsoft SQL Server Compact 4.0 (.NET Framework)• MDF – Microsoft SQL Server Database Dile (SqlClient)

43

WALK THROUGH: Connecting to a Database13. From the Toolbox, under the Data section, in Design view drag-and-drop a Gridview control to your Web Form.

14. Click on the GridView control to display GridView tasks, and in Choose Data Source select New Data Source to bring up the Data Source Configuration window.

15. Select the SQL Database icon, then specify an ID for the data source (e.g., lec4demo2), the click OK.

44

WALK THROUGH: Connecting to a Database16. Select your data source from the Configure Data Source window, the click Next.

45

WALK THROUGH: Connecting to a Database17. Click Next in the new window.

18. Depending on your table, you can configure the Select Statement on how you want to display your data.

46

WALK THROUGH: Connecting to a Database19. In the Test Query window, click the Test Query button to preview your data from the data source.

47

WALK THROUGH: Connecting to a Database20. Click the Finish button, to see how your data source has been set up on your Web Form.

21. Run the program to see how it looks in a web page.

48

WALK THROUGH: Connecting to a Database22. It's up to you how simply or complicated you set up your queries using query builder.

49

Connecting to DataOf course there are other ways to connect to data and databases with Visual Studio, and we will examine as we continue through the quarter. There are also some things I am going to allow you to research and experiment with yourself, giving you just enough rope to shoot yourselves in the foot—just like real developers!

To Be Continued On Tuesday

50

Suggested Data Connection Links of Interest

• Connecting to Databases in ASP.NET (MSDN)

• Connecting to an Access Database (MSDN)

• Connecting to an ODBC Database (MSDN)

• Database Access (TutorialsPoint)

• How to Connect to a Database in ASP.NET (Udemy)

• Connecting to the Database in ASP.NET (Lynda.com)

51

Lecture 04: In-Class ExerciseFrom the menu bar, select Lectures and go to the Lectures 04 bar and select Lecture 04 ICE to begin working on today's in-class exercises.