Vous êtes sur la page 1sur 51

Adding Code to a

Microsoft ASP.NET Web Form

Module 5

Module 5: Adding Code to a MS ASP.NET Web Form Youll learn about the various methods that can be used for adding code to your MS ASP.NET Web application Plus! youll learn about event procedures for Web server controls, how to use them, and the order which they work Then, learn how to use code-behind pages for adding code to Web pages

Lastly, learn how to page events Page_Load event

Overview
Using Code-Behind Pages

Adding Event Procedures to Web Server Controls


Using Page Events

Lesson: Using Code-Behind Pages


How to Implement Code

Writing Inline Code


What are Code-Behind Pages? Understanding How Code-Behind Pages Work

How you put in VB.NET in Web Form??? & How its work???

How to Implement Code


Three methods for adding code: Put code in the same file as content (mixed) Put code in a separate section of the content file (inline code)

Put code in a separate file (code-behind pages)


Code-behind pages are the Visual Studio .NET default

There are 3 ways to Implement Code:


Mixed Code
The code is in the same file as the Web content Intermingled with HTML Least preferred difficult to read and work

Inline Code
Separate SCRIPT section of the same file as HTML content

Code-behind
Code is in a separate file from the HTML content The code called code-behind-page

Writing Inline Code


Code and content in the same file Different sections in the file for code and HTML

<HTML> <asp:Button id="btn" runat="server"/> </HTML> <SCRIPT Language="vb" runat="server"> Sub btn_Click(s As Object, e As EventArgs) Handles btn.Click ... End Sub </SCRIPT> <HTML> <asp:Button id="btn" runat="server"/> </HTML> <SCRIPT Language="c#" runat="server"> protected void btn_Click(object sender, System.EventArgs e) { . . . } </SCRIPT>

What are Code-Behind Pages?


The programming logic is in a separate file than the visual elements on the page A code-behind page can only contain code in a single language Cannot mix VB.NET and C# in the same codebehind page Separate
Logic
Programming code (VB.NET @ C#)

Design
UI (HTML)

What are Code-Behind Pages?


Separation of code from content
Developers and UI designers can work independently
Single file Separate files

code <tags>
Form1.aspx

<tags>
Form1.aspx

code
Form1.aspx.vb or Form1.aspx.cs

Each Web page contain all of the programming logic for a single Web page Each Web page in a Web application has its own code-behind page By default, a code-behind page has the same name as the Web page with which it is associated; however, the code-behind page also has an .aspx.vb or .aspx.cs

Understanding How Code-Behind Pages Work


Create separate files for user interface and interface

logic
Use @ Page directive to link the two files Pre-compile or JIT-compile

Default.aspx.vb

Default.aspx
<%@ Page Language="VB"

Partial Class _Default protected Sub cmd1_Click() End Sub End Class

CodeFile="Default.aspx.vb" Inherits="_Default" %>

Understanding How Code-Behind Pages Work


For code behind page to work each .aspx page must be associated with a code behind page and that code-behind page must be compiled before information is returned to a requesting client browser Although each Web Form page consists of two separate files (the .aspx page and code-behind page), the two files form a single unit when the Web application is run The code-behind page can either be precompiled by Visual Studio .NET when you build the Web application or can be just-in-time compiled the first time that a user accesses the page

Linking the two files


The .aspx page must be associated with the code-behind page Visual Studio .NET adds the following two attributes to the @Page directive of the .aspx page to accomplish this association:
CodeFile This is the attribute that VS .NET uses internally to associated the files Inherits This attribute allows the .aspx page to inherit classes and objects from the codebehind page

An example @Page
VB.NET
<%@ Page Language=vb CodeFile=Page1.aspx.vb Inherits=_Default %>

C#
<%@ Page Language=c# CodeFile=Page1.aspx.cs
Inherits=_Default %>

Understanding How Code-Behind Pages Work


Create separate files for user interface (.aspx) and interface logic (.aspx.cs) Although each Web Form page consists of 2 separate files the 2

files form a single unit when the Web application is run

Lesson: Adding Event Procedures to Web Server Controls


What are Event Procedures? Client-Side Event Procedures Server-Side Event Procedures Multimedia: Client-Side and Server-Side Events Creating Event Procedures

Interacting with Controls in Event Procedures

What are Event Procedures?


Action in response to a users interaction with the controls on the page

Event Procedures
Dynamic, interactive Web Forms typically react to user input

Event procedures are used to handle user interactions on a Web Form


When user interacts with a Web Form, an event is generated You design your Web application to perform an appropriate task when the event is generated An event procedure is the action that occurs in response to the generated event Example Many Web Form allow the user to enter information and then click a Submit button For example, an event procedure for an event might be to send the user information to MS SQL Server database

There are 2 types of event procedures:

1- CLIENT 2- SERVER-SIDE

Client-Side Event Procedures


Typically, used only with HTML controls only Interpreted by the browser and run on the client

Does not have access to server resources action done on client-side (no access to server!)
Time-saving & performance Uses <SCRIPT language="language">

Internet

.HTM Pages

CLIENT-SIDE (validation)
Client-side event procedures Are event that are handled on the computer that request the Web Form (the client) When an event is generated no information is sent to server For example, you cannot use client-side script to access a SQL Server database The client browser interprets the code and perform actions Uses for client-side event procedures Are useful for event that you want to happen immediately because they do not require a round trip to the Web server (sending information to the Web server and waiting for a response) Do not send information to Web server and wait for response

Server-Side Event Procedures


Used with both Web and HTML server controls

Code is compiled and run on the server


Have access to server resources Use <SCRIPT language="vb" runat="server"> or <SCRIPT language=cs" runat="server">

Internet

.ASPX Pages

Unlike client-side event procedures, server-

side event procedures require information to be sent to the Web server for processing
Although these is a time cost to using serverside event procedures, they are much

more powerful than client-side event


procedures

SERVER-SIDE
Server-side event procedures
Consists of compiled code that exist on the web server Can be used to handle events that are generated from both Web and HTML server controls

Have access to server resources


You specify a server-side event procedure by using the runat=server attribute in the script tag, as following:
VB.NET

<SCRIPT language=vb runat=server>


C# <SCRIPT language=c# runat=server>

Client-Side and Server-Side Events

Client-Side and Server-Side Events (cont.)


1. The client requests an ASP.NET page from the Web server. 2. The server returns a page containing HTML and script to the client. The page includes a text box control and a Submit button. The page
also contains client-side script that validates the contents of the text box.
3. The user enters invalid information into the text box, and the client-side script generates a message box.

4. Because no information has been sent to the server, client-side processing reduces network traffic and response times.

Client-Side and Server-Side Events (cont.)


5. The user corrects the information in the text box, and then clicks the Submit button. 6. The information is validated on the client side, and then sent to the server, where server-side processing can take place. 7. The server repeats the validation and stores the information from the text box in a database.

8. Because the client-side script cannot access server resources, server-side processing offers a greater range of security & flexibility in data processing.

Creating Event Procedures


Visual Studio .NET declares variables and creates an event procedure template

protected WithEvents cmd1 As System.Web.UI.WebControls.Button protected Sub cmd1_Click(ByVal s As System.Object, _ ByVal e As System.EventArgs) Handles cmd1.Click

protected System.Web.UI.WebControls.Button cmd1; protected void InitializeComponent() { this.cmd1.Click += new System.EventHandler(this.cmd1_Click); this.Load += new System.EventHandler(this.Page_Load); } protected void cmd1_Click(object s, System.EventArgs e)

Using the Handles keyword adds many event procedures to one event

Object
Is the object firing of the event

EventArgs
Is specific information for the event

Creating Event Procedures


Involves 2 steps
1. Create the control that generates the event on the Web Form 2. Provide code-behind page that is needed to handled the event

When you double-click a control in VS .NET, VS .NET declares a variable (with the same name as the id attribute of the control) and creates an event procedure template When you use VB.NET, VS.NET also adds the Handles keyword, which attaches the event procedure to the control The Handles keyword allows you to create multiple event procedures for a single event

Instructor-Led Practice: Creating

an
Event Procedure

Interacting with Controls in Event Procedures


Read the properties of Web server controls
strGreeting = "Hello " & txtName.Text strGreeting = "Hello " + txtName.Text;

Output responses to other Web server controls


lblGreeting.Text = "new text" lblGreeting.Text = "new text";

In many Web applications, you need to read from and write to controls on a form You can do this within server-side event procedures Within a server-side event procedure, you can read information from a server control For example, if you have the following form with a Textbox and a Button control:
<FORM id=Form1 runat=server> <asp:TextBox id=txtName runat=server /> <asp:Button id=cmd1 runat=server /> </FORM>

When the user clicks the button, you can read the text that the user typed into the text box The following code assigns the string variable strGreeting to a concatenation of the text Hello and the text in the txtName text box:
VB.NET Dim strGreeting As String = Hello & txtName.Text C# string strGreeting = Hello + txtName.Text

For example, if a user typed Ahmad in the txtName text box, the strGreeting variable would contain the text string Hello Ahmad.

Lesson: Using Page Events


Understanding the Page Event Life Cycle The PostBack Process Handling Page.IsPostback Events Linking Two Controls Together

Understanding the Page Event Life Cycle


Page_Init
Control events Change Events Action Events

Page_Load Textbox1_Changed Button1_Click Page_Unload


Page is disposed

Understanding the Page Event Life Cycle


When an ASP.NET page is requested, there are a series of page events that occur. These events always occur in the same order, which is referred to as the page event life cycle.

The page event life cycle consists of the following page events, which occur in the following order: 1. Page_Init. This page event initializes the page by creating and initializing the Web server controls on the page. (start loading the page start / boot) 2. Page_Load. This page event runs every time the page is requested. 3. Control events. This page event includes change events (for example,Textbox1_Changed) and action events (for example, Button1_Click). 4. Page_Unload. This page event occurs when the page is closed or when the control is passed to another page. (close the page)
The end of the page event life cycle includes the disposal of the page from memory

Postbacks
In ASP.NET, forms are designed to post information back to the sending ASP.NET page for processing This process is called postback Postbacks may occur with certain user actions By default, only Button click events cause form to be posted back to the server However, of you set the AutoPostBack property of a control true, a postback is forced for events of that control

The Postback Process


For example, the following HTML code is an example of using AutoPostBack on a list box. Every time the user changes the value of the list box, the SelectedIndexChanged event will be raised on the server and it will update the text box:

The Postback Process (cont.)


<asp:DropDownList id="ListBox1" runat="server"

AutoPostBack="True">
<asp:ListItem>First <asp:ListItem>Second </asp:DropDownList> Choice</asp:ListItem> Choice</asp:ListItem>

Protected Sub ListBox1_SelectedIndexChanged _ (ByVal s As System.Object, ByVal e As System.EventArgs) _ Handles ListBox1.SelectedIndexChanged TextBox1.Text=ListBox1.SelectedItem.Value End Sub

The Postback Process (cont.)

Postback Forms
User request a page from a server server returns the page to the user In the page
ListBox Label Submit Button

When user change the solution in the list box and then clicks the submit button, the information is sent back to server If you want the new value of the list

box to be sent to the server immediately dont have to wait for user to click Submit button

Set ListBox controls AutoPostBack property to TRUE

The Postback Process (cont.)


In this animation, you will see how forms work in ASP.NET and how the Page_Load event can be coded to only run the first time a page is displayed, and how controls can be made to post immediately to the server. 1. The first time that a user requests a page from the server, the test for Page.IsPostBack in the Page_Load event succeeds and the code in the block runs. In this example, the code fills in a list

box.
2. The server then returns the page to the user. In this example, the page has a ListBox, a blank Label, and a Submit button on it. 3. When the user changes the selection in the list box, and then clicks the Submit button, the information is sent back to the server.

The Postback Process (cont.)


4. The server can determine that this is a page that is being posted back to itself, and so the test for Page.IsPostBack in the Page_Load event fails and the code in the block does not run. 5. Instead, the event procedures for the controls on the form (the list box and the button) run and in this scenario, the list box event procedure changes the label to reflect the new list box selection. 6. Then, the server returns the updated information to the client. The user sees the same page, but the label has now changed to reflect the list box selection. 7. If you want the new value of the list box to be sent to the server immediately, and not wait for the user to click the Submit button, you can set the

list box controls AutoPostBack property to True.

The Postback Process (cont.)


8. With the AutoPostBack property set to True, as

soon as the user changes the selection in the list box, the information is sent to the server.

9. The server updates the label to reflect the change, and then sends the updated information back to the client.

Demonstration:

Handling Events

Practice: Placing Events

In Order

Handling Page.IsPostback Events


Page_Load fires on every request
Use Page.IsPostBack to execute conditional logic
protected void Page_Load(object sender, System.EventArgs e) { if (!Page.IsPostBack) { // executes only on initial page load } //this code executes on every request } protected Sub Page_Load(ByVal s As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then 'executes only on initial page load End If 'this code executes on every request End Sub

Page.IsPostBack prevents reloading for each postback

Review
Using Code-Behind Pages

Adding Event Procedures to Web Server Controls


Using Page Events

Vous aimerez peut-être aussi