0% found this document useful (0 votes)
16 views

Chapter 4.1 Introduction To

The document provides an introduction to ASP.NET, describing what it is and its key components. It then details the lifecycle of an ASP.NET application, outlining the stages it goes through from request to response. Finally, it lists the events that occur during the ASP.NET page lifecycle.

Uploaded by

pyakurel.sharad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Chapter 4.1 Introduction To

The document provides an introduction to ASP.NET, describing what it is and its key components. It then details the lifecycle of an ASP.NET application, outlining the stages it goes through from request to response. Finally, it lists the events that occur during the ASP.NET page lifecycle.

Uploaded by

pyakurel.sharad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Author: Sharad Pyakurel

Introduc on to ASP.NET
ASP.NET is a web development framework developed by Microso . It allows developers to build
dynamic websites, web applica ons, and web services. The "ASP" in ASP.NET stands for Ac ve
Server Pages. ASP.NET contains a rich set of tools, libraries, and features that make it easier to
develop robust and scalable web applica ons. It includes components such as the ASP.NET Web
Forms for building page-based applica ons, ASP.NET MVC (Model-View-Controller) for building
more flexible and testable applica ons, and ASP.NET Web API for crea ng RESTful web services.

ASP.NET runs on the server and generates HTML pages that are sent to the client's web browser.

Life cycle of ASP.NET Applica on:


The ASP.NET Web Forms applica on lifecycle refers to the sequence of events and stages that
occur during the processing of a Web Forms page within an ASP.NET applica on. Following are
different stages in asp.net applica on lifecycle:
Author: Sharad Pyakurel

1. Page Request:
- It is the first step of the page life cycle. When a user makes a request to a Web Forms
page, the ASP.NET run me receives the request and iden fies the requested page based
on the URL. ASP.NET decides whether the page needs to be parsed and compiled, or just
a cached version of the page can be sent in response without running the page.

2. Page Start:
- Page proper es such as Request and Response are set in the start stage. The page also
decides whether the request is a post back or a new request. Page Start helps in crea ng
two objects: request and response. The request holds all the informa on which the user
sent, while the response contains all the informa on that is sent back to the user.

3. Page Ini aliza on:


- At this stage, the controls on the page are assigned unique ID by se ng the Uniquid
property. Master page and themes are also applied to the page, if applicable. The Init
event is raised, allowing to perform ini aliza on tasks before the page is loaded and
processed. Developers can create or dynamically modify controls, set ini al property
values in this event.

4. Page Load:
- Page Load helps to load all the control proper es of an applica on. If the current request
is a post back, control proper es are loaded with informa on recovered from view state
and control state.

5. Valida on and event Handling:


- Valida on happens when the execu on of an applica on is successful. The “IsValid”
property is set based on the valida on results, and if valida on fails, the page remains in
the post back state.
- If the request is a post back, the related event handler is invoked.

6. Page Rendering:
- The page is rendered, genera ng the HTML output that will be sent back to the client's
browser. i.e., In ASP.NET Web Forms, page rendering involves the process of genera ng
the HTML markup that is sent to the client's web browser. This process occurs on the
server side and is handled by the ASP.NET run me.
Author: Sharad Pyakurel

- The “Render" method of each control is called, and the HTML markup is generated based
on the control's proper es and state.

7. Page Unload:
- The “Unload” event will be triggered a er the page is rendered. Some tasks such as
cleanup tasks, release resources, or final logging before the page lifecycle ends can be
performed in Unload stage.
- The rendered page is sent to the client and page proper es, such as Response and
Request, are unloaded and all cleanup done.

Events during ASP.NET Page Life Cycle


- PreInit: This event is the first in the page life cycle. It checks the “IsPostBack” property
and determines whether the page is a post back. It sets the themes and master pages,
creates dynamic controls, and gets and sets profile property values. This event can be
handled by overloading the “OnPreInit” method or crea ng a “Page_PreInit”
handler.

protected void Page_PreInit(object sender, EventArgs e)


{
lblStageName.Text += "<br/>" + "PreInit";
}

protected void Page_PreInit(object sender, EventArgs e)


{
string themeName = "mythem";
if (themeName != null)
this.Page.Theme = themeName;
else
this.Page.Theme = "Light";
}

1. Init: This event reads and ini alizes control proper es and occurs a er all the controls
are ini alized. This event reads or ini alizes control proper es. The server controls are
loaded and ini alized from the webform view state.

protected void Page_Init(object sender, EventArgs e)


{
lblStageName.Text += "<br/>" + "Init";
}
Author: Sharad Pyakurel

2. InitComplete: This event is raised when the ini aliza on of the page and its controls
is complete. At this stage, you can make final changes to the controls before the page
is loaded. This event can be used to make changes in ViewState and process
ini aliza on tasks to be completed.

protected void Page_InitComplete (object sender, EventArgs e)


{
lblStageName.Text += "<br/>" + "InitComplete";
}

3. PreLoad: This event occurs before the page is loaded and is commonly used to
perform tasks such as data binding or loading data into controls. This event is raised
for each control recursively, star ng from the outermost control and moving inward.
PreLoad occurs before the post back data is loaded in the controls. This event can be
handled by overloading the OnPreLoad method.

protected override void OnPreLoad(EventArgs e)


{
lblStageName.Text += "<br/>" + "PreLoad";
}

4. Load: The Load event is raised a er the PreLoad event. It is commonly used to load
data into controls and make final adjustments before rendering the page. This event
also can be used to handle user input and perform any necessary processing.

protected void Page_Load(object sender, EventArgs e)


{
if (!Page.IsPostBack)
{
//Set Some default Values//
//Load default applica on data//
}

lblStageName.Text += "<br/>" + "Load";


}

5. LoadComplete: This event is raised when the page and all its controls have been
loaded. The loading process is completed, control event handlers are run, and page
Author: Sharad Pyakurel

valida on takes place. This event can be handled by overloading the OnLoadComplete
method.

protected void Page_LoadComplete(object sender, EventArgs e) {


lblStageName.Text = lblStageName.Text + "<br/>" + "LoadComplete";
}

6. PreRender: The PreRender event occurs just before the rendering stage of the page.
It gives you a chance to make final modifica ons to the page or its controls before the
HTML markup is generated. The PreRender event will be triggered just before the page
is sent to the browser, allowing you to make any final modifica ons.

protected override void OnPreRender(EventArgs e)


{
base.OnPreRender(e);

// Dynamically change the text of a label control


lblMessage.Text = "Welcome, " + GetUserDetails();
}

7. SaveStateComplete: This event is raised a er view state and control state have
been saved for the page and for all controls. Any changes to the page or controls at
this point will be ignored. We can use this event to perform tasks that require the view
state to be saved, but that do not make any changes to controls. The
SaveStateComplete event is not commonly used for typical page opera ons, as most
tasks can be accomplished using earlier page events.

protected override void OnSaveStateComplete(EventArgs e)


{
base.OnSaveStateComplete(e);

// Perform database opera ons


SaveDataToDatabase();

// Update session variables


UpdateSessionVariables();

// Apply final changes to the page


ApplyFinalChanges();
}
Author: Sharad Pyakurel

8. Render: This event renders the output of the page. It is triggered when the page is
ready to render its HTML markup. In this event, you can modify the final HTML output
if needed. The Render method generates the client-side HTML, Dynamic Hypertext
Markup Language (DHTML), and script that are necessary to properly display a control
at the browser.

protected override void Render(HtmlTextWriter writer)


{
// Added HTML element
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.Write("This is a Finally created DIV element.");
writer.RenderEndTag();
base.Render(writer);
}

9. Unload: The Unload event is the final event in the page life cycle. It occurs a er the
page has been fully rendered and sent to the client. This event is used for cleanup
tasks such as closing database connec ons or releasing resources.

protected override void OnLoad(EventArgs e)


{
base.OnLoad(e);

Page.Response.Write("<h1>onload: " + Page.IsPostBack.ToString()+"</h1>");


}
Author: Sharad Pyakurel

Basic Components of ASP.NET Web Applica on


ASP.NET Webform applica on follows a component-based approach, where the applica on is
built using various components and controls. Key components of an ASP.NET Web Forms
applica on include following:

1. Web Forms: Web Forms are the main building blocks of an ASP.NET Web Forms
applica on. They are represented by .aspx files that define the layout and structure of the
web pages. It allows mechanism to collect user input, display data, and respond to user
ac ons. The web forms framework is based on the server-side programming model.
(frmLogin.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="frmLogin.aspx.cs"


Inherits="MyWebApp.frmLogin" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td colspan="2" style="text-align: center">User Login
</td>
</tr>
<tr>
<td>Userid:</td>
<td>
<asp:TextBox ID="txtUserId" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="txtPassword" TextMode="Password"
runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnLogin" runat="server" Text="Login" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Author: Sharad Pyakurel

- The runat="server" a ribute indicates that these HTML elements are server controls,
which means they can be accessed and manipulated from server-side code.

2. Server Controls: Server controls are a set of pre-built components that encapsulate
common func onality and provide a higher level of abstrac on. They can be added to
web forms and are responsible for rendering HTML markup, handling user input, and
performing server-side processing. Server controls include bu ons, text boxes, labels,
drop-down lists, and data controls like GridView and DataList, etc.
3. Code-Behind Files: Each Web Form typically has a corresponding code-behind file with a
.aspx.cs or .aspx.vb extension. These code-behind files contain the logic and event
handlers for the web form. They are used to handle user input, perform data access and
manipula on, and interact with other components of the applica on.
(frmLogin.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyWebApp
{
public partial class frmLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

protected void btnLogin_Click(object sender, EventArgs e)


{
Response.Write("Hello and Welcome <b>"+ txtUserId.Text.Trim()+"</b>!");
}
}
}

4. Web.config file: The web.config file is an XML configura on file that contains se ngs and
configura ons for an ASP.NET Web Forms applica on. It includes informa on about
applica on-specific se ngs, connec on strings, authen ca on se ngs, session state
configura on, and more. The web.config file can be used to customize the behavior and
se ngs of the applica on.
5. State Management: ASP.NET Web Forms provides mechanisms for managing the state of
web applica ons. ViewState allows storing and retrieving values across postbacks,
Author: Sharad Pyakurel

maintaining the state of controls between requests. Session state allows storing user-
specific data across mul ple requests, and Applica on state enables storing data
accessible by all users of the applica on.
6. Data Controls: ASP.NET Web Forms includes a rich set of data controls that simplify data
access and display. These controls are used to bind data from various data sources (such
as databases or XML files) to user interface elements. Examples of data controls include
GridView, ListView, DataList, and Repeater.
7. Valida on Controls: ASP.NET Web Forms provides a set of valida on controls that enable
developers to perform client-side and server-side valida on of user input. These controls
allow us to define valida on rules and display error messages if the input does not meet
the specified criteria. Valida on controls include RequiredFieldValidator,
RegularExpressionValidator, CompareValidator, and CustomValidator,etc.
8. Master Pages: Master Pages provide a consistent layout and structure across mul ple
pages in a web applica on. They define the common elements like headers, footers,
naviga on menus, and placeholders for content. By using Master Pages, developers can
easily maintain a consistent user interface across the applica on and separate the
presenta on layer from the content.
9. Global.asax file: The Global.asax file contains applica on-level events and se ngs. It
allows you to handle applica on-level events like Applica on_Start and Session_Start,
configure rou ng, and define global error handling.

 What is AutoEventWireup?
The AutoEventWireup a ribute is used to automa cally wire up event handlers for
controls in a web form without explicitly subscribing to the events in the code-behind file.
If AutoEventWireup is true, ASP.NET finds methods that match a specific naming
conven on and a aches them to the appropriate events automa cally. By default,
AutoEventWireup=true means ASP.NET automa cally wires up event handlers by
matching the naming conven on of the controls in the web form by default.

For example, if there is a bu on control with an ID "btnOK" and you want to handle its
Click event, we can define a method in code-behind file with the following signature:
Author: Sharad Pyakurel

protected void btnOK_Click(object sender, EventArgs e)


{
// Event handling code
}

- ASP.NET will automa cally wire up this method to the Click event of the "btnOK" control
since it follows the naming conven on of "ControlID_EventName".
- If AutoEventWireup a ribute is false, we need to manually subscribe to the events in the
code-behind using the += operator or the AddHandler method as following.

protected void Page_Load(object sender, EventArgs e)


{
btnOK.Click += btnOK _Click; // Manually subscribing to the Click event
}

protected void btnOK_Click(object sender, EventArgs e)


{
// Event handling code
}

You might also like