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

Asp Net

ASP NET TEXTBOOK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Asp Net

ASP NET TEXTBOOK
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

ASP NET

It is a web framework designed and developed by Microsoft. It is used to develop websites, web
applications and web services. It provides fantastic integration of HTML, CSS and JavaScript. It was first
released in January 2002. It is built on the Common Language Runtime (CLR) and allows programmers to
write code using any supported .NET language.

Web Application are two types: -

1)Static web application

2)Dynamic web application

Static web application: -

The Application whose output is common for all the users static web application can be developed by
using Ui Technologies

example HTML, JS, CSS

Dynamic web application: -

The Whose Application will change based on user, Location, Time, search, Dynamic web Application Can
be using developed by using

Example: Java…, .net, Python, SQL and UI Technologies

Desktop Application: -

1) The Application that was installed on single Computer

2) The Desktop can be developed by using programming languages Like c#.net, java, python, c, c++

3) We Have to Install desktop Application on users Computer

4) We Cannot access Desktop Application Via Browser

5) Webserver is Optional for Desktop Application

6) If we place Desktop application on webserver then end user will Download the application and
install
7) Desktop Application in single user Application

Ex: - Notepad, calculator, games…etc.…

Web Application: -

1) The Application that was deployed was webserver and can be accessible Via Browser and
internet are called as web applications

2) web plications can be developed by using Technologies and frameworks like asp.net,
asp.netMVC

3) We Cannot Install Web application

4) Brower is mandatory to access web application

5) Webserver is mandatory for web application

Ex: - iis, apache, JBoss

6) If we deployed web Application on webserver so that end user will directly access the application
via browser and internet

7) Web Application is Multiuser Application

Ex: - Facebook, gmail, instgram, etc…..

Application Life Cycle

1. Application Start

The webserver executes the application start when a user requests an application for access. In this
method, it sets all global variables to default.

2. Object Creation

Object creation holds all the HTTP Context, HTTP Request, and HTTP Response by the webserver. It also
contains information about the request, cookies, and browsing information.
3. HTTP Application

HTTP Application is an object created by the webserver. It helps to process all the subsequent information
that is sent to the user.

4. Dispose

Dispose is an event that is called before the application is destroyed. It also helps to release manually
unmanaged resources when the objects are no longer needed.

5. Application End

Application End is the last stage of the application life cycle. It helps to unload the memory.

Page Life Cycle


1. Page Request

Page Request is the first step of the page life cycle. When a user request is made, the server checks the
request and compiles the pages. Once the compilation is done, the request is sent back to the user.

2. Page Start

Page Start helps in creating two objects: request and response. The request holds all the information
which the user sent, while the response contains all the information that is sent back to the user.

3. Page Initialization

Page Initialization helps to set all the controls on the pages. It has a separate ID, and it applies themes to
the pages in this step.

4. Page Load

Page Load helps to load all the control properties of an application. It also helps to provide information
using view state and control state.

5. Validation

Validation happens when the execution of an application is successful. It returns two conditions: true and
false. If execution is successful, it returns true, otherwise false.

6. Event Handling

Event Handling takes place when the same pages are loaded. It is a response for the validation. When the
same page is loaded, a Post back event is called, which checks the page’s credentials.

7. Rendering

Rendering happens before it sends all the information back to the user. And all this information is stored
before being sent back.

8. Unload
Unload is a process that helps in deleting all unwanted information from the memory once the output is
sent to the user.
Page Life Cycle Events

PreInit: This event occurs when the start stage is done but before the initialization stage.

Init: This event reads and initializes control properties and happens after all the controls are initialized.

InitComplete: This happens at the conclusion of the page’s initialization stage. The event makes changes
to the view state that we want to ensure are persisted at the end of the subsequent postback.

PreLoad: PreLoad occurs at the conclusion of the event-handling stage, and is used for tasks that need all
other page controls to be loaded.

Load: Load is raised initially for the page, then recursively for the child controls.

Control events: This takes care of handling specific control events like button control clicks.

Load Complete: This event is used for many tasks that need other controls found on the page to be
loaded. Load Complete occurs at the conclusion of the event-handling stage.

PreRender: This event kicks in after the page object has created the controls necessary to render the
page.

PreRenderComplete: This event happens once the pre-render stage is complete.

SaveStateComplete: This event is raised when the view and control states are saved for both the page and
all the controls.

Render: Render isn’t actually an event; rather, it’s a method that the Page object calls for each control.

Unload: This event is first raised for each control, then for the page itself.
ASP.NET Web Forms

ASP.NET Web Forms is a part of the ASP.NET web application framework. Web Forms are pages that your
users request using their browser. These pages can be written using a combination of HTML, client-script,
server controls, and server code. When users request a page, it is compiled and executed on the server by
the framework, and then the framework generates the HTML markup that the browser can render. An
ASP.NET Web Forms page presents information to the user in any browser or client device.

Using Visual Studio, you can create ASP.NET Web Forms. The Visual Studio Integrated
Development Environment (IDE) lets you drag and drop server controls to lay out your Web Forms page.
You can then easily set properties, methods, and events for controls on the page or for the page itself.
These properties, methods, and events are used to define the web page's behavior, look and feel, and so
on.

We have 2 Type of Controls

1. Server Controls

2. HTML Controls

Server Controls
Control Applicable Events Description
Name

Label None It is used to display text on the HTML page.

TextBox TextChanged It is used to create a text input in the form.

Button Click, Command It is used to create a button.

LinkButton Click, Command It is used to create a button that looks similar to the
hyperlink.

ImageButton Click It is used to create an imagesButton. Here, an image


works as a Button.

Hyperlink None It is used to create a hyperlink control that responds


to a click event.

DropDownList SelectedIndexChanged It is used to create a dropdown list control.

ListBox SelectedIndexCnhaged It is used to create a ListBox control like the HTML


control.

DataGrid CancelCommand, It used to create a frid that is used to show data. We


EditCommand, can also perform paging, sorting, and formatting very
DeleteCommand, easily with this control.
ItemCommand,
SelectedIndexChanged,
PageIndexChanged,
SortCommand,
UpdateCommand,
ItemCreated,
ItemDataBound

DataList CancelCommand, It is used to create datalist that is non-tabular and


EditCommand, used to show data.
DeleteCommand,
ItemCommand,
SelectedIndexChanged,
UpdateCommand,
ItemCreated,
ItemDataBound

Repeater ItemCommand, It allows us to create a non-tabular type of format for


ItemCreated, data. You can bind the data to template items, which
ItemDataBound
are like bits of HTML put together in a specific
repeating format.

CheckBox CheckChanged It is used to create checkbox.

CheckBoxList SelectedIndexChanged It is used to create a group of check boxes that all work
together.

RadioButton CheckChanged It is used to create radio button.

RadioButtonList SelectedIndexChanged It is used to create a group of radio button controls


that all work together.

Image None It is used to show image within the page.

Panel None It is used to create a panel that works as a container.

PlaceHolder None It is used to set placeholder for the control.

Calendar SelectionChanged, It is used to create a calendar. We can set the default


VisibleMonthChanged, date, move forward and backward etc.
DayRender

AdRotator AdCreated It allows us to specify a list of ads to display. Each time


the user re-displays the page.

Table None It is used to create table.

XML None It is used to display XML documents within the HTML.

Literal None It is like a label in that it displays a literal, but allows us


to create new literals at runtime and place them into
this control.

HTML Controls

Controls Description
Name

Button It is used to create HTML button.


Reset Button Resets all other HTML form elements on a form to a default value

Submit Automatically POSTs the form data to the specified page listed in the Action attribute in
Button the FORM tag

Text Field Gives the user an input area on an HTML form

Text Area Used for multi-line input on an HTML form

File Field Places a text field and a Browse button on a form and allows the user to select a file
name from their local machine when the Browse button is clicked

Password An input area on an HTML form, although any characters typed into this field are
Field displayed as asterisks

CheckBox Gives the user a check box that they can select or clear

Radio Button Used two or more to a form, and allows the user to choose one of the controls

Table Allows you to present information in a tabular format

Image Displays an image on an HTML form

ListBox Displays a list of items to the user. You can set the size from two or more to specify how
many items you wish show. If there are more items than will fit within this limit, a scroll
bar is automatically added to this control.

Dropdown Displays a list of items to the user, but only one item at a time will appear. The user can
click a down arrow from the side of this control and a list of items will be displayed.

Horizontal Displays a horizontal line across the HTML page


Rule

Create a Web Application


This project contains a default.aspx file which is a startup file. When we run the project this file executes
first and display a home page of the site.

We can see its output on the browser by selecting view in browser option
PostBack in ASP.NET

Postback is actually sending all the information from client to web server, then web server process all
those contents and returns back to the client. Most of the time ASP control will cause a post back (e. g.
buttonclick) but some don't unless you tell them to do In certain events ( Listbox Index
Changed,RadioButton Checked etc..) in an ASP.NET page upon which a PostBack might be needed.

IsPostBack is a property of the Asp.Net page that tells whether or not the page is on its initial load or if a
user has perform a button on your web page that has caused the page to post back to itself. The value of
the Page.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.

Is Postback is normally used on page _load event to detect if the web page is getting generated due to
postback requested by a control on the page or if the page is getting loaded for the first time.
Example:

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

// generate form;

else

//process submitted data;

Grid View Explanation


GridView.EditIndex Property

The zero-based index of the row to edit. The default is -1, which indicates that no row is being edited.
ASP.NET provides the following validation controls:

RequiredFieldValidator

RangeValidator

CompareValidator

RegularExpressionValidator

CustomValidator

ValidationSummary

RequiredFieldValidator

The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a
text box to force input into the text box.

syntax :

<asp:RequiredFieldValidator ID="rfvcandidate"

runat="server" ControlToValidate ="ddlcandidate"

ErrorMessage="Please choose a candidate"

InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

RangeValidator

The CompareValidator control compares a value in one control with a fixed value or a value in another
control.

syntax :
<asp:CompareValidator ID="CompareValidator1" runat="server"

ErrorMessage="CompareValidator">

</asp:CompareValidator>

RegularExpression

The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular
expression. The regular expression is set in the ValidationExpression property.

syntax :

<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"

ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidator

The CustomValidator control allows writing application specific custom validation routines for both the
client side and the server side validation.

syntax :

<asp:CustomValidator ID="CustomValidator1" runat="server"

ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator>

ValidationSummary

The ValidationSummary control does not perform any validation. Its purpose is to display a summary of all
the errors on the page.

syntax:
<asp:ValidationSummary ID="ValidationSummaryControl"

runat="server" DisplayMode=”BulletList” ShowSummary=”true”

HeaderText=”List of Errors” />

State Management in ASP.NET

State management is the process by which you maintain state and page information over multiple
requests for the same or different pages.

Types of State Management

ASP.NET supports two types of state management approaches:

Client-Side State Management Techniques - To maintain the state of values on the client’s machine, we
use the client-side state management techniques

Server-Side State Management Techniques - To maintain the state of values on the server’s machine, we
use the server-side state management techniques

CLIENT-SIDE STATE MANAGEMENT TECHNIQUES

View state and Control State

Cookies

Query Strings

Hidden Fields

SERVER-SIDE STATE MANAGEMENT TECHNIQUES

Application State

Session State
Cache

SERVER-SIDE STATE MANAGEMENT TECHNIQUES

Session

An important technique to maintain state. It is used to store identity and information; information is
stored in the server using Sessionid.

To start the user session -

Example

protected void btnSubmit_Click(object sender, EventArgs e)

Session["UserName"] = txtName.Text;

Response.Redirect("Home.aspx");

Session Event Two types -

Session starts - Raised every time a new user requests without a session ID.

Example

void Session_Start(object sender, EventArgs e)

Session["Master"] = "~/Master.master";

Session end - Raised everytime the user ends the session or a time out occurs.

Example

void Session_End(object sender, EventArgs e)

Response.Write("Session_End");

}
The session is stored in the following ways in ASP.NET:

InProcMode - Default session mode. When the server starts, the session value is stored, and when the
server is restarted, it ends.

State Server Mode - Session date is made to store on a separate server in this mode.

SQL Server Mode - It’s a secure mode in which the session is made to store in the database.

Custom Mode - Session data is generally stored in InProcMode, SQL Server Mode, etc. In case we want to
store using any other techniques, we use the custom mode.

Application

It is a server-side management state and is also known as the application-level state management. This is
mainly used to store user activity in server memory and application events.

This is further classified into three types:

Application start - The event begins with the start of the domain.

Example

Void ApplicationStart(object sender, EventArgs e)

Application["ApplicationstartMessage"] = "Welcome to Simplilearn";

Application error - This is used to manage/handle an error or exception that had been previously
unhandled.

Example

void ApplicationError(object sender, EventArgs e)

// Unhandled exception code block

}
Application end - Whenever the domain ends, this ends as well.

Example

Void ApplicationEnd(object sender, EventArgs e)

Application["ApplicationEndMessage"] = "Applications are Closed";

Cache

This is stored on the server-side, and it is used to implement page caching and data caching. A cache is
primarily used to set expiration policies.

Example snippet

Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1));

***

Client-Side State Management in ASP.NET

Cookie

One of the smallest but important parts of the ASP NET, it is used to store the session and application
information of the user. It can be constant and temporary and works with browser requests. The server
can read these cookies from the client-side and perform data abstraction.

There are two types of cookies that are available -

Persistence - The Persistence cookie works along with Time and Date.

Example
Response.Cookies["CookiesName"].Value = "Testing Cookies";

//setting the expire time

Response.Cookies["CookiesName"].Expires = DateTime.Today.AddHours(2);

Non-Persistence - Temporary cookie created with application access and closed application is discarded.

Example

Response.Cookies["CookiesName"].Value = "Testing Cookies";

Control State

It is a technique used to maintain data work in order, properly. We use Control State to use the view state
without the possibility of it being disabled by the user.

Example

if (!IsPostBack)

lblmsg1.Text = "Welcome to Simplilearn!";

lblmsg2.Text = "Welcome to Simplilearn!";

We use a customized control state to control the one being displayed when these two messages are
being displayed on the PostBack event.

Hidden Field
This field is used to store values on the client-side. The hidden field works on request and is not displayed
on the browser.

Example

if (HiddenField.Value != null)

int dat = Convert.ToInt32(HiddenField.Value) + 1;

HiddenField.Value = dat.ToString();

Labels.Text = dat.ToString();

Viewstate

It is used to manage page-level state and is used for storing, sending, and receiving information.

We can store small values in Viewstate, but it is pretty easy to apply since it does not require any server
resources. The page using Viewstate becomes heavy if more data is stored.

Example

if (ViewState["User_Name"] != null)

lblName.Text = ViewState["User_Name"].ToString();

Query String

The query string is used to store the value in the URL.

Example

Response.Redirect("ShowStringValue.aspx?Username=" + txtUsername.Text);
Output

Custom Session Mode

There are several custom session storage mechanisms that ASP.NET applications can use. Custom session
state store providers enable developers to create their own session state storage mechanisms. This is the
most flexible option, but also the most difficult to implement. Developers can also use a custom session
state manager. This option is less flexible than using a custom session state store provider, but is easier to
implement. Finally, developers can use a custom session ID generator. This option is the simplest to
implement, but provides the least flexibility. Developers who want to use a custom session storage
mechanism must first decide which option is best for their needs.

for example, we can work with below client and server side states for Custom

Client-Side State Management

Cookies

Hidden Fields

ViewState

Server-Side State Management

Application State

Session State

Cache

You might also like