Module 5 Net 2005

Embed Size (px)

Citation preview

  • 7/30/2019 Module 5 Net 2005

    1/51

    Module 5

    Adding Code to a

    Microsoft ASP.NET Web Form

  • 7/30/2019 Module 5 Net 2005

    2/51

    Module 5:Adding Code to a MS ASP.NET Web Form

    Youll learn about the various methodsthatcan be used foradding codeto your MS

    ASP.NET Web application

    Plus! youll learn about event proceduresfor

    Web server controls, how to use them, and theorder which they work

    Then, learn how to use code-behind pages for

    adding code to Web pages

    Lastly, learn how to page eventsPage_Loadevent

  • 7/30/2019 Module 5 Net 2005

    3/51

    Overview

    Using Code-Behind Pages

    Adding Event Procedures to Web Server

    Controls

    Using Page Events

  • 7/30/2019 Module 5 Net 2005

    4/51

    Lesson: Using Code-BehindPages

    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???

  • 7/30/2019 Module 5 Net 2005

    5/51

    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-behindpages)

    Code-behind pages are the Visual Studio.NET default

  • 7/30/2019 Module 5 Net 2005

    6/51

    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 SeparateSCRIPT section of the same fileas

    HTML content

    Code-behind

    Code is in a separate file from the HTMLcontent

    The code called code-behind-page

  • 7/30/2019 Module 5 Net 2005

    7/51

    Writing Inline Code

    Code and content in the same file

    Different sections in the file for code and HTML

    Sub btn_Click(s As Object, e As EventArgs) Handles btn.Click...End Sub

    protected void btn_Click(object sender, System.EventArgs e){. . .

    }

  • 7/30/2019 Module 5 Net 2005

    8/51

    What are Code-Behind Pages?

    The programming logic is in a separate filethan 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 code-behind page

    Separate

    Logic Programming code (VB.NET @ C#)

    Design

    UI (HTML)

  • 7/30/2019 Module 5 Net 2005

    9/51

    What are Code-Behind Pages?

    Separation of code from content Developers and UI designers can work independently

    Form1.aspx Form1.aspx Form1.aspx.vb

    or Form1.aspx.cs

    code

    code

    Separate filesSingle file

  • 7/30/2019 Module 5 Net 2005

    10/51

    Each Web page contain all of theprogramming logic for a single Web page

    Each Web pagein a Web application has itsown code-behind page

    By default, a code-behind page has the samename as the Web pagewith which it isassociated; however, the code-behind page

    also has an .aspx.vbor.aspx.cs

  • 7/30/2019 Module 5 Net 2005

    11/51

    Understanding How Code-BehindPages Work

    Create separate files foruser interface and interfacelogic

    Use @ Page directive to link the two files

    Pre-compile or JIT-compile

    Default.aspx

    Default.aspx.vb

    Partial Class _Default

    protected Sub cmd1_Click()

    End Sub

    End Class

  • 7/30/2019 Module 5 Net 2005

    12/51

    Understanding How Code-BehindPages Work

    For code behind page to work each .aspx page mustbe associated with a code behind page and thatcode-behind page must be compiled beforeinformation 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 twofiles form a single unit when the Web application isrun

    The code-behind page can either be precompiled byVisual Studio .NET when you buildthe Web application

    or can bejust-in-timecompiled the first time that a useraccesses the page

  • 7/30/2019 Module 5 Net 2005

    13/51

    Linking the two files

    The .aspx page must be associatedwith thecode-behind page

    Visual Studio .NET adds the following two

    attributes to the @Page directive of the .aspxpage to accomplish this association:

    CodeFile This is the attribute that VS .NETuses internally to associated the files

    Inherits This attribute allows the .aspx page

    to inherit classes and objects from the code-behind page

  • 7/30/2019 Module 5 Net 2005

    14/51

    An example @Page VB.NET

    C#

  • 7/30/2019 Module 5 Net 2005

    15/51

    Understanding How Code-BehindPages 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 asingle unit when the Webapplication is run

  • 7/30/2019 Module 5 Net 2005

    16/51

    Lesson: Adding EventProcedures to Web ServerControls

    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

  • 7/30/2019 Module 5 Net 2005

    17/51

    What are Event Procedures?

    Action in response to a usersinteraction with the controls on thepage

  • 7/30/2019 Module 5 Net 2005

    18/51

    Event Procedures

    Dynamic, interactiveWeb Forms typically react to userinput

    Event procedures are used to handle user interactionson a Web Form

    When user interacts with a Web Form, an event isgenerated

    You design your Web application to perform anappropriate 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 eventmight be to send the user information to MS SQL

    Server database

  • 7/30/2019 Module 5 Net 2005

    19/51

    There are 2 types of event procedures:

    1- CLIENT2- SERVER-SIDE

  • 7/30/2019 Module 5 Net 2005

    20/51

    Client-Side Event Procedures

    Internet .HTM

    Pages

    Typically, used only with HTML controls only

    Interpreted by the browser and run on the client

    Does not have access to server resources actiondone on client-side (no access to server!)

    Time-saving & performance

    Uses

  • 7/30/2019 Module 5 Net 2005

    21/51

    CLIENT-SIDE (validation)

    Client-side event procedures

    Are event that are handled on the computer that requestthe Web Form (the client)

    When an event is generatedno 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

    Areuseful for event that you want to happenimmediately because they do not require a roundtrip to the Web server (sending information to the Webserver and waiting for a response)

    Do not send information to Web server and wait for

    response

  • 7/30/2019 Module 5 Net 2005

    22/51

    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 or

  • 7/30/2019 Module 5 Net 2005

    23/51

    Unlike client-side event procedures, server-side event procedures requireinformation to be sent to the Web

    server for processing Although these is a time cost to using server-

    side event procedures, they are much

    more powerful than client-side eventprocedures

  • 7/30/2019 Module 5 Net 2005

    24/51

    SERVER-SIDE

    Server-side event procedures Consists ofcompiled code that exist on the

    web server

    Can be used to handle events that are generated

    fromboth Web and HTML server controlsHave access to server resources

    You specify a server-side event procedure by

    using the runat=server attribute in the scripttag, as following:

  • 7/30/2019 Module 5 Net 2005

    25/51

    Client-Side and Server-SideEvents

    http://d/Default.htm
  • 7/30/2019 Module 5 Net 2005

    26/51

    Client-Side and Server-SideEvents (cont.)

    1. The client requests an ASP.NET page fromthe Web server.

    2. The server returns a page containing HTMLand script to the client. The page includes a

    text box control and a Submit button. The pagealso contains client-side script that validates thecontents of the text box.

    3. The user enters invalid information into the textbox, and the client-side script generates a

    message box.

    4. Because no information has been sent to theserver, client-side processing reduces networktraffic and response times.

  • 7/30/2019 Module 5 Net 2005

    27/51

    Client-Side and Server-SideEvents (cont.)

    5. The user corrects the information in the textbox, 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 offersa greater range of security & flexibility indata processing.

  • 7/30/2019 Module 5 Net 2005

    28/51

    Creating Event Procedures

    Visual Studio .NET declares variables and creates anevent procedure template

    Using the Handles keyword adds many eventprocedures to one event

    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)

    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

  • 7/30/2019 Module 5 Net 2005

    29/51

    Object Is the object firing of the event

    EventArgs

    Is specific information for the event

  • 7/30/2019 Module 5 Net 2005

    30/51

    Creating Event Procedures

    Involves 2 steps

    1. Create the control that generates the eventon the Web Form

    2. Provide code-behind page that is needed tohandled 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) andcreates an event procedure template

    When you use VB.NET, VS.NET also adds the

    Handles keyword, which attaches the eventprocedure to the control

    TheHandles

    keyword allows you to create

    multiple event procedures for a single event

  • 7/30/2019 Module 5 Net 2005

    31/51

    Instructor-Led Practice:

    Creatingan

    Event Procedure

  • 7/30/2019 Module 5 Net 2005

    32/51

    Interacting with Controls inEvent Procedures

    Read the properties of Web servercontrols

    Output responses to other Webserver controls

    lblGreeting.Text = "new text"

    strGreeting = "Hello " & txtName.Text

    strGreeting = "Hello " + txtName.Text;

    lblGreeting.Text = "new text";

  • 7/30/2019 Module 5 Net 2005

    33/51

    In many Web applications, you need to readfrom 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:

  • 7/30/2019 Module 5 Net 2005

    34/51

    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 variablestrGreeting to a concatenation of the textHello and the text in the txtName text box:

    For example, if a user typed Ahmad in the

    txtName text box, the strGreeting variablewould contain the text string Hello Ahmad.

  • 7/30/2019 Module 5 Net 2005

    35/51

    Lesson: Using Page Events

    Understanding the Page Event LifeCycle

    The PostBack Process

    Handling Page.IsPostback Events

    Linking Two Controls Together

  • 7/30/2019 Module 5 Net 2005

    36/51

    Understanding the Page EventLife Cycle

    Page_Load

    Page_Unload

    Textbox1_Changed

    Button1_Click

    Page is disposed

    Page_Init

    Control events

    Change Events

    Action Events

    Understanding the Page Event Life Cycle

  • 7/30/2019 Module 5 Net 2005

    37/51

    Understanding the Page Event Life Cycle

    When an ASP.NET page is requested, there are a seriesof page eventsthat occur. These events always occur in

    the same order, which is referred to as the page eventlife cycle.

    The page event life cycle consists of the following pageevents, which occur in the following order:

    1. Page_Init. This page event initializes the page bycreating and initializing the Web server controls

    on the page. (start loading the page start / boot)2. Page_Load. This page event runsevery time the

    page is requested.3. Control events. This page event includes change

    events (for example,Textbox1_Changed) and actionevents (for example, Button1_Click).

    4. Page_Unload. This page event occurs when thepage is closedor when the control is passed toanother page. (close the page)

    The end of the page event life cycle includes the disposalof the page from memory

  • 7/30/2019 Module 5 Net 2005

    38/51

    Postbacks In ASP.NET, forms are designed to post

    information back to the sendingASP.NET page for processing

    This process is called postback

    Postbacks may occur with certain useractions

    By default, only Button click eventscause form to be posted back to the

    server

    However, of you set the AutoPostBackproperty of a control true, a postback isforced for events of that control

  • 7/30/2019 Module 5 Net 2005

    39/51

    The Postback Process

    For example, the following HTML

    code is an example of using

    AutoPostBack on a list box. Everytime the user changes the value of

    the list box, the

    SelectedIndexChanged event will be

    raised on the server and it will updatethe text box:

  • 7/30/2019 Module 5 Net 2005

    40/51

    The Postback Process (cont.)

    First Choice

    Second Choice

  • 7/30/2019 Module 5 Net 2005

    41/51

    The Postback Process (cont.)

    http://localhost/var/www/ITD%2020703/New%20Folder/PPSlideASPNet05/2310B_05A002.htm
  • 7/30/2019 Module 5 Net 2005

    42/51

    Postback Forms

    User request a page from a server server returns thepage to the user

    In the page

    ListBox

    Label

    Submit Button

    When user change the solution in the list box and thenclicks the submit button, the information is sent back toserver

    If you want the new value of the list box to be sentto the server immediatelydont have to

    wait for user to click Submit button

    Set ListBox controls

    AutoPostBack property to TRUE

  • 7/30/2019 Module 5 Net 2005

    43/51

    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 thefirst time a page is displayed, and how controls can bemade to post immediately to the server.

    1. The first time that a user requests a page from the server, the

    test forPage.IsPostBack in the Page_Load event succeedsandthe code in the block runs. In this example, the code fills in a listbox.

    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 thenclicks the Submit button, the information is sent back to the server.

  • 7/30/2019 Module 5 Net 2005

    44/51

    The Postback Process (cont.)

    4. The server can determine that this is a page that is beingposted back to itself, and so the test forPage.IsPostBack inthe Page_Load event failsand the code in the block does notrun.

    5. Instead, the event proceduresfor 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 listbox selection.

    6. Then, the server returns the updated information to theclient. The user sees the same page, but the label has nowchanged 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 userto click the Submit button, you can set thelist box controls AutoPostBack property toTrue.

  • 7/30/2019 Module 5 Net 2005

    45/51

    The Postback Process (cont.)

    8. With the AutoPostBack property set to True, as soon asthe user changes the selection in thelist box, the information is sent to theserver.

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

  • 7/30/2019 Module 5 Net 2005

    46/51

    Demonstration:

    Handling Events

  • 7/30/2019 Module 5 Net 2005

    47/51

    Practice:

    Placing Events

    In Order

  • 7/30/2019 Module 5 Net 2005

    48/51

  • 7/30/2019 Module 5 Net 2005

    49/51

    H dli P I P tb k

  • 7/30/2019 Module 5 Net 2005

    50/51

    Handling Page.IsPostbackEvents

    Page_Load fires on every request

    UsePage.IsPostBackto execute conditional logic

    Page.IsPostBackprevents reloading for each postback

    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

    protected void Page_Load(object sender, System.EventArgs e)

    { if (!Page.IsPostBack)

    {

    // executes only on initial page load

    }

    //this code executes on every request

    }

  • 7/30/2019 Module 5 Net 2005

    51/51

    Review

    Using Code-Behind Pages

    Adding Event Procedures to Web Server

    Controls

    Using Page Events