0% found this document useful (0 votes)
35 views51 pages

Unit Iv

The document discusses ASP.NET Web Forms and the key aspects of building web forms applications using Visual Studio. It describes how web forms hide the stateless nature of HTTP and simplify web development. It also provides tables listing the various server controls and HTML controls available in ASP.NET Web Forms.

Uploaded by

Adinath
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)
35 views51 pages

Unit Iv

The document discusses ASP.NET Web Forms and the key aspects of building web forms applications using Visual Studio. It describes how web forms hide the stateless nature of HTTP and simplify web development. It also provides tables listing the various server controls and HTML controls available in ASP.NET Web Forms.

Uploaded by

Adinath
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/ 51

Unit-IV

Essentials ASP.NET
Assistant Prof: Bhise G.G

Some people will consider ASP.NET a step backwards. ASP.NET Web Forms did a
great deal of work to hide the realities of the Web. HTTP is a fundamentally
stateless protocol and HTML can be a difficult markup language to learn. In some
ways, ASP.NET Web Forms try to hide both of these realities behind Visual
Studio and behind the ASP.NET Web Forms subsystem.
Developers became used to the idea that they could write a button onto a form in
the Visual Basic designer, double-click that button and have a Button_Click event
wired up automatically. When ASP.NET was introduced, it offered this kind of
functionality for Web development. This was huge and its significance shouldn’t be
underestimated. While ASP.NET has been maligned by some for hiding too much,
it made Web development accessible to a large number of developers who were
having trouble wrapping their heads around the details of the HTML/HTTP
development model. ASP.NET brought this familiar control and event model to
Web development.

A Basic Web Forms Application


Head over to Visual Studio and go to FileNew Project and create a new ASP.NET
Web Application in Visual Studio. This should be a Web Forms application, not an
ASP.NET MVC application. Now, open up default.aspx and drag a button, a label
and a text box over onto the design surface as shown in Figure D-1.
Next, simply double-
click the TextBox. Notice
that you’ll be taken to the
Web Form’s code-behind and your cursor is positioned in the middle of a
TextChanged event. This is a simple action you’ve taken, but it has profound
implications. Sit back and drink in the simplicity of what you did and think about
what is being hidden.
Remember that HTTP is a completely stateless protocol. The browser does a GET
request for a page, the user types in a TextBox and submits an HTML Form,
sending a POST to the server. As far as the server is concerned, the GET and the
POST are not related at all. They are distinct and discrete. It’s up to the
programmer and the programming model to correlate the two events and choose
they are related. The developers of ASP.NET Web Forms explicitly decided that
as a programming model it would:

-Represent a page as a ‘‘control tree’’ where each control was accessible via the
programmer on the server-side.

-Give these server-side controls events like their desktop counterparts, and as
such, hide as much HTTP and HTML as is reasonable.

-Make state-management as transparent as pos


Web Forms, represented by .aspx files, are the core of any ASP.NET Web Forms
website. They are the actual pages that users see in their browsers when they
visit your site.

A form is a section of an HTML document where you put input controls (text
boxes, check boxes, radio buttons, and pull-down lists).

ASP.NET Web Forms

Web Forms are web pages built on the ASP.NET Technology. It executes on the
server and generates output to the browser. It is compatible to any browser to any
language supported by .NET common language runtime. It is flexible and allows us
to create and add custom controls.

We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated
Development Environment) that allows us to drag and drop server controls to the
web forms. It also allows us to set properties, events and methods for the controls.
To write business logic, we can choose any .NET language like: Visual Basic or Visual
C#.

Web Forms are made up of two components: the visual portion (the ASPX file), and
the code behind the form, which resides in a separate class file.

ASP.NET provides various controls like: server controls and HTML controls for
the Web Forms. We have tables all these controls below.

Server Controls

The following table contains the server-side controls for the Web Forms.

Control Name Applicable Events Description

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


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

DataList CancelCommand, It is used to create datalist that is


EditCommand, non-tabular and used to show data.
DeleteCommand,
ItemCommand,
SelectedIndexChanged,
UpdateCommand,
ItemCreated,
ItemDataBound

Repeater ItemCommand, It allows us to create a non-tabular


ItemCreated, type of format for data. You can
ItemDataBound bind the data to template items,
which 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


VisibleMonthChanged, can set the default date, move
DayRender forward and backward etc.

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
These controls render by the browser. We can also make HTML controls as server
control. we will discuss about this in further our tutorial.

Controls Description
Name

Button It is used to create HTML button.

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

Submit Automatically POSTs the form data to the specified page listed in
Button the Action attribute in 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
Field this field are displayed as asterisks

CheckBox Gives the user a check box that they can select or clear
Radio Used two or more to a form, and allows the user to choose one of the
Button 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

ASP.NET Web Forms Features

ASP.NET is full of features and provides an awesome platform to create and


develop web application. Here, we are discussing these features of Web Forms.

o Server Controls
o Master Pages
o Working with data
o Membership
o Client Script and Client Frameworks
o Routing
o State Management
o Security
o Performance
o Error Handling

Server Controls

Web Forms provides rich set of server controls. These controls are objects that
run when the page is requested and render markup to the browser. Some Web
server controls are similar to familiar HTML elements, such as buttons and text
boxes. It also provides controls that we can use to connect to data sources and
display data.

Master Pages

It allowsus to create a consistent layout for the pages in our application. This page
defines the look and feel and standard behavior that we want for all of the pages
in our application. When users request the content pages, they merge with the
master page to produce output that combines the layout of the master page with
the content from the content page.

Working with Data

In an ASP.NET Web Forms application, we use data-bound controls to automate the


presentation or input of data in web page UI elements such as tables and text boxes
and drop-down lists.

Membership

Project's Account folder contains the files that implement the various parts of
membership: registering, logging in, changing a password, and authorizing access.
Additionally, ASP.NET Web Forms supports OAuth and OpenID. These
authentication enhancements allow users to log into your site using existing
credentials, from such accounts as Facebook, Twitter and Google.

Client Script and Client Frameworks

We can enhance the server-based features of ASP.NET by including client-script


functionality in ASP.NET Web Form pages. We can use client script to provide a
richer, more responsive user interface to the users. We can also use client script
to make asynchronous calls to the Web server while a page is running in the browser.

Routing

We can configure URL routing of our application. A request URL is simply the URL
a user enters into their browser to find a page on our web site. We use routing to
define URLs that are semantically meaningful to users and that can help with
search-engine optimization (SEO).

State Management

ASP.NET Web Forms includes several options that help you preserve data on both
a per-page basis and an application-wide basis.

Security

Developing a secure application is most important aspect of software development


process. ASP.NET Web Forms allow us to add extensibility points and configuration
options that enable us to customize various security behaviors in the application.

Performance

Web Forms provides good performance and allows us to modify performance related
to page and server control processing, state management, data access, application
configuration and loading, and efficient coding practices.

Debugging and Error Handling

We can diagnose problems that occur in our Web Forms application. Debugging and
error handling are well supported within ASP.NET Web Forms so that our
applications compile and run effectively.

ASP.NET Web Forms Project

We are using Visual studio 2017 to create web project. It includes the following
steps:
1. Creating a new project

Click on the file menu from the menu bar and select new -> project.

Select Project type

It provides couple of choices but we selecting ASP.NET Web Application.

Select Project Template


After selecting project types, now, it asks for the type of template that we want
to implement in our application.

Here, we are selecting Web Forms as because we are creating a Web Forms
application.

after clicking ok, it shows project in solution explorer window that looks like the
below.
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 as we did
below.
Finally, it shows output in the browser like this:
Create a New Web Form

Here, we are using the project that we created in last topic. To add a new web form
in our existing project, first select project then right click and add new item.

Select web forms option in left corner and then select web form and hit add button.
Now click on the add button and this form will add to our project.

After adding form, we can see that this is now in our project as we have shown in
the below image.

Double click on this form and this will show some auto generated code like this:
// user-form.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="user-


form.aspx.cs"
Inherits="asp.netexample.user_form" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Welcome to the Web Forms!</h2>
</div>
</form>
</body>
</html>
After running it on the browser it yields the following output.
Directory Structure in ASP.NET
Every web application should have a well-planned directory structure. For example,
you’ll probably want to store images in a separate folder from where you store
your web pages. Or you might want to put public ASP.NET pages in one folder and
restricted ones in another so you can apply different security settings based on
the directory. Along with the directories you create, ASP.NET also uses a few
specialized subdirectories, which it recognizes by name (see Table 5-2). Keep in
mind that you won’t see all these directories in a typical application. Visual Studio
will prompt you to create them as needed.

Directory
1.Bin
Contains all the compiled .NET components (DLLs) that the ASP.NET web
application uses. For example, if you develop a custom component for accessing a
database , you’ll place the component here. ASP.NET will automatically detect the
assembly, and any page in the web application will be able to use it. This seamless
deployment model is far easier than working with traditional COM components,
which must be registered before they can be used (and often reregistered when
they change).

2) App_Code
Contains source code files that are dynamically compiled for use in your
application. You can use this directory in a similar way as the Bin directory; the
only difference is that you place source code files here instead of compiled
assemblies.
3) App_GlobalResources
Stores global resources that are accessible to every page in the web application.
This directory is used in localization scenarios, when you need to have a website in
more than one language. Localization isn’t covered in this book, although you can
refer to Pro ASP.NET 3.5 in C# (Apress, 2007) for more information.

4) App_LocalResources
Serves the same purpose as App_GlobalResources, except these resources are
accessible to a specific page only.

5) App_WebReferences
Stores references to web services that the web application uses. For more
information about web services

6) App_Data
Stores data, including SQL Server 2005 Express Edition database files and XML
files. Of course, you’re free to store data files in other directories.

7) App_Themes
Stores the themes that are used by your web application.

http://www.infinitezest.com/articles/understanding-asp-net-directory-
structure.aspx

ASP.NET Compilation Model

In order for application code to service requests by users, ASP.NET must first
compile the code into one or more assemblies. Assemblies are files that have the
file name extension .dll. You can write ASP.NET code in many different languages,
such as Visual Basic, C#, J#, and others. When the code is compiled, it is
translated into a language-independent and CPU-independent representation called
Microsoft Intermediate Language (MSIL). At run time, MSIL runs in the context
of the .NET Framework, which translates MSIL into CPU-specific instructions for
the processor on the computer running the application.

There are many benefits to compiling application code including:

• Performance Compiled code is much faster than scripting languages such as


ECMAScript or VBScript because it is a closer representation to machine
code and does not require additional parsing.
• Security Compiled code is more difficult to reverse engineer than non-
compiled source code because it lacks the readability and abstraction of a
high-level language. Additionally, there are obfuscation tools that make
compiled code even more resistant to reverse engineering.
• Stability Code is checked at compile time for syntax errors, type safety, and
other problems. By catching these errors at build-time you can eliminate
many errors in your code.
• Interoperability Because MSIL code supports any .NET language, you can use
assemblies that were originally written in other languages in your code. For
example, if you are writing an ASP.NET Web page in C#, you can add a
reference to a .dll file that was written in Visual Basic.

The ASP.NET compilation architecture includes a number of features including:

• Multiple language support.


• Automatic compilation.
• Flexible deployment.
• Extensible build system.

The following sections describe each of these features.

Multiple Language Support

In ASP.NET 2.0 you can use different languages such as Visual Basic and C# in
the same application because ASP.NET will create multiple assemblies, one for
each language. For code stored in the App_Code folder, you can specify a
subfolder for each language. For more information on the App_Code folder,
see Shared Code Folders in ASP.NET Web Sites.
Automatic Compilation

ASP.NET automatically compiles your application code and any dependent


resources the first time a user requests a resource from the Web site. In
general, ASP.NET creates an assembly for each application directory (such as
App_Code) and one for the main directory. (If files in a directory are in different
programming languages, then separate assemblies will be created for each
language.) You can specify which directories are compiled into single assemblies in
the Compilation section of the Web.config file.

Flexible Deployment

Because ASP.NET compiles your Web site on first user request, you can simply
copy your application's source code to the production Web server. However,
ASP.NET also provides precompilation options that allow you to compile your Web
site before it has been deployed, or to compile it after it has been deployed but
before a user requests it. Precompilation has several advantages. It can improve
the performance of your Web site on first request because there will be no lag
time while ASP.NET compiles the site. Precompiling can also help you find errors
that might otherwise be found only when a user requests a page. Finally, if you
precompile the Web site before you deploy it, you can deploy the assemblies
instead of the source code.

You can precompile a Web site using the ASP.NET compiler tool
(ASPNET_Compiler.exe). The tool that provides the following precompilation
options:

• In-place compilation This option performs the same compilation that occurs
during dynamic compilation. Use this option to compile a Web site that has
already been deployed to a production server.
• Non-updateable full precompilation Use this to compile an application and
then copy the compiled output to the production server. All application code,
markup, and UI code is compiled into assemblies. Placeholder files such as
.aspx pages still exist so that you can perform file-specific tasks such as
configure permissions, but the files contain no updateable code. In order to
update any page or any code you must precompile the Web site again and
deploy it again.
• Updateable precompilation This is similar to non-updateable full
precompilation, except that UI elements such as .aspx pages and .ascx
controls retain all their markup, UI code, and inline code, if any. You can
update code in the file after it has been deployed; ASP.NET will detect
changes to the file and recompile it. Note that code in a code-behind file (.vb
or .cs file) built into assemblies during precompilation, and you therefore
cannot change it without going through the precompilation and deployment
steps again.

For more information, see ASP.NET Precompilation Overview.

Extensible Build System

ASP.NET uses BuildProvider classes to build items such as .aspx pages, .ascx files,
and global resources. You can extend and customize the ASP.NET build system to
compile custom resources by creating classes that inherit from
the BuildProvider class. For example, you could add a new file type and then write
a BuildProvider that builds that particular type.

https://www.guru99.com/asp-net-controls-webforms.html

Code behind Model


In Code Behind model of ASP.NET the business logic place a separate file. For
this example we need to create two files, one web form name Default.aspx and
another file name Default.aspx.cs.

The Default.aspx holds two Label control, one TextBox control and one Button
control. The all business logic need to place in Default.aspx.cs file. Here is the
source code of both files.
Default.aspx
Working with Web form Controls

https://www.msdotnet.co.in/2013/06/web-forms-controls-in-
aspneti.html#.YbXENNVBzIU

Asp.net is Fully Based on Controls. Before Making any application ,I will learn
First about the Asp.Net Controls. If you will understand the Use of Controls then
you can easily make any Application without any problem in Asp.Net.There are
some Types of controls which are used in Asp.Net.

▪ Web Forms Standard controls.


▪ Navigation Controls
▪ Validation Controls

Note:- Whenever you will use Web Forms Controls in your Application then First
write one Namespace Which is Given below:

using System.Web.UI.WebControls;

Because All Web Forms Controls comes Under this Namespace .

Web Forms Controls:-

There are some Web Forms Controls which is given below with Real Time
Example:-

1. Label Control
2. TextBox control
3. Button control
4. Literal control
5. PlaceHolder control
6. HiddenField control
7. FileUpload control
8. Image control
9. ImageButton control
10. ImageMap control

1.) Label Control:-


The Label Control is basically used to display the Information(Text) on Web
Forms .Any end User can not Edit(change) the Label Information.
Properties of Label Control:-
There are some important properties of Label controls.

▪ Text:-It is used to change the Label control information(text).


▪ Font:- It is used to sets the font of the Label text.
▪ ForeColor:- It is used to sets the text color in the Label.
▪ Height:- It is used to Specify the height of the Label Control.
▪ BackColor :-It is used to Sets the Background color of the Label control.
▪ BorderWidth:-It is used to Sets the Border color of the Label control.
▪ BorderStyle:-It is used to Sets the Style of the Label control.
▪ AccessKey:-It is used to Navigate the Web Server control.
There are some steps to implement the Label control on the Web Form which is
given below:

Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select


ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop Label
and Button control from Toolbox on the Web Form as Given below:

Step :2 Now Double Click on Click Button and Write the following codes which is
shown below:
Partial Class Default2
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles


Button1.Click
Label1.Text = "You can easily display any information inside it"

End Sub
End Class

Step :3 Now Run The Program(Press F5) and Press the Click Button.
Output:

2.) TextBox Control:-

The TextBox control is used to input the Data(text).Any end user can easily enter
the text in this control.
Properties of TextBox Control:-
There are some important properties of TextBox controls.

▪ Text:-It is used to sets the text in TextBox Control.


▪ TextMode:- It is used to sets the mode of the TextBox Control as Single
Mode,Multiline or Password.
▪ Rows:-It is used to sets the number of rows display in a TextBox(Multiline).
▪ MaxLength:->It is used to sets the maximum number of character alloweded
in a TextBox control.
▪ ReadOnly:-It is used to read the contents by the end used but can not change
it.
▪ Columns:-It is used to sets the width of character in TextBox.
▪ AutoCompleteType:-It is used to sets a value that indicates the Auto
Complete behavior of the TextBox control.
▪ AutoPostBack:-It is used to handle the event when the TextBox control lose
focus.
▪ CauseValidation:-It is used to set a value that validate the TextBox
control(client,server).
▪ TextChange:-It is an event.It occurs when the end user change the text of
the TextBox control.
3.) Button Control:-> The Button control is used to create an Event and send
request to the web server.
Properties of Button Control:-
There are some important properties of Button controls.

▪ Text:- It is used to sets the text to be displayed on the Button Control.


▪ Click:-It is an Event that occurs when the Button is clicked.
▪ Command:- It is also an Event that occurs when the Button is clicked.It is
used whenever we are using multiple Button on one page.
▪ CommandName:-It is used to sets the command Name associated with the
Button control that is passed to the command event.
▪ OnClientClick:-It is used to sets the client side script that executes when a
Button click event is fired.
▪ CauseValidation:- It is used to sets the validation that is perform or not
when we click the Button control.
There are some steps to implement the TextBox and Button controls on the
Web Form which is given below:
Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop
TextBox,Label and Button control from Toolbox on the Web Form as Given below:
Step :2 Now Double Click on Button Control and Write the following which is given
below:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
String str = TextBox1.Text;
Label2.Text = str;
}
}
Step :3 Now Run The program(press F5) and click the Button.
output:
4.) Literal Control:-
It is similar to Label control but there are some differences
and similarities which is given below.

▪ Literal and Label control both are used to display the text(information) on
the web form.
▪ On Browser side Label control is converted to HTML 'Span' tag but Literal
control is not converted in any HTML tag.
▪ We can provide formatting to the Label control but not to the Literal control.
▪ If we want to show some HTML code and java script code the we used mainly
Literal control ,not Label control.Encoding Mode is used with Literal control
only.
Properties of Literal Control:-

There are some important properties of Literal controls.

▪ Mode:- IT IS A Literal control property called Mode which can be changed


as Transform,Encode and Pass Through.
▪ Text:-It is used to sets the caption displayed in the Literal.
There are some steps to implement the Literal and Label controls on the Web
Form which is given below:
Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop
Literal,Label and Button control from Toolbox on the Web Form as Given below:
Step :2 Now Double click on Click button and write the following codes which is
given below:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Literal_and_label_controls_ : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
Literal1.Text = "Hello Asp.net Website I am Literal Control";
Label2.Text = "Hello Asp.net Website I am Label Control";
}
}

Step :3 Now Run the program(press F5) and press the click button.
output:-
5.) PlaceHolder Control:-

It is known as container control in Asp.Net.It is mainly used to store the value of


other controls.You can Add controls to a Web Form by using
the Controls.Add() Method.
There are some steps to implement the PlaceHolder control on the Web Form
which is given below:
Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop
PlaceHolder and Button control from Toolbox on the Web Form as Given below:

Step :2 Now Double click on Click button and write the following codes which is
given below:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class placeHoldercontrol : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(TextBox1);
}
}

Step :3 Now Run The Program(Press F5) and Press the Click Button.

Output:
6. )HiddenField Control:-
It is used to display the value stored in the HiddenField control in the Label
control.It stores the information in the form of Strings.

There are some steps to implement the HiddenField control on the Web Form
which is given below:

Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select


ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop
HiddenField,TextBox,Label and Button control from Toolbox on the Web Form as
Given below:

Step :2 Now Double click on Click button and write the following codes which is
given below:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class HiddenFieldcontrol : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
HiddenField1.Value = TextBox1.Text;
Label2.Text = HiddenField1.Value;
}
}

Step :3 Now Run The Program(Press F5) and Press the Click Button.

Output:

7. )FileUpload Control:-
It is basically used to Upload the File on the server using SaveAs() method on the
click Event.When user browse a File and after browse click the Upload button
then File is automatically Upload on the Server.

There are some steps to implement the FileUpload control on the Web Form
which is given below:
Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select
ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop
FileUpload,Label and Button control from Toolbox on the Web Form as Given
below:

Step :2 Now Double click on Click button and write the following codes which is
given below:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Fileuploadcontrol : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs("I:/" + FileUpload1.FileName);
Label2.Text = "File"+" " + FileUpload1.FileName +" "+"is uploaded
successfully";
}
}

Step :3 Now Run The Program(Press F5) ,Browse File from your computer and
Press the Click Button.
Output:

8. ) Image Control:-
It is used to display an image on a web page.

Properties of Image control:-


There are some important properties of Image control controls.

▪ Alternate Text:- It is used to display alternate text when the image is not
present.
▪ ImageAlign:-It is used to sets the alignment of image control on the web
page.
▪ ImageUrl:-It is used to sets the path to an image to display in the image
control.
▪ Font:-It is used to increase or decrease font of the image control text.
▪ DescriptionUrl:-It is used to set the location to a detailed description for
the image.
There are some steps to implement the Image control on the Web Form which is
given below:

Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select


ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop
Image control from Toolbox on the Web Form as Given below:

Step :2 Now copy the Image from computer and paste in the Website folder as
shown below:

Step :3 Now Go Image Property-->click on ImageUrl Property-->select your


image.
You will see following output:

9. ) ImageButton Control:-
It is used to display the image on Button instead of text.Properties of
ImageButton is same as Button property.

10. ) ImageMap Control:-


It is used to provide various links(hotspots) to navigate to other web
page,depending on the place where the user clicks.
Properties of ImageMap Control:-
There are some important properties of ImageMap control.

▪ Hotspots:-It obtains a group of Hotspot Object that is defined in a


ImageMap.
▪ Target:-It is used to sets target window to show the web page when the
ImageMap control clicked.
▪ Enabled:- It is used to sets a value indicating whether the control can
respond to the user interaction.
There are some steps to implement the Image control on the Web Form which is
given below:

Step :1 First Open Your Visual Studio-->File-->New-->Web Site-->Select


ASP.NET Empty Web Site-->OK-->Open Solution Explorer-->Right Click on Web
Site-->Add New Item -->Select Web Form--> click Add-->Now drag and drop
ImageMap,ImageButton and Label control from Toolbox on the Web Form as
Given below:

Step :2 Now copy the Image from computer and paste in the Website folder as
shown below:
Step :3 Now Go properties of ImageMap and ImageButton and Select
appropriate image by Clicking ImageUrl.
Step :4 Now go Properties of ImageMap control and select( Collection).Add new
hotspots as shown below:

Step :5 Now Run the Program(Press F5) and Click the Image Button.
output:
Note:- I have implemented this Application with some controls,Download it and
Implement on Your System One by one.
First open This application in Your Visual studio(copy whole Web Form and paste
your website folder)-->Go Solution Explorer-->Right click on Web form Which you
want to Run-->click Set As a Start Page.Then you can Easily Run Each Web page.
For More:-

Navigation Controls

To make it easy to show relevant pages in your site using a Menu, a TreeView, or a
SiteMapPath, ASP.NET uses an XML-based file that describes the logical
structure of your website. By default, this file is called Web.sitemap. This file is
then used by the navigation controls in your site to present relevant links in an
organized way. Simply by hooking up one of the navigation controls to the
Web.sitemap file, you can create complex user interface elements like fold-out
menus or a tree view

Navigation control in ASP.NET manages the data passing between ASPX pages.
Web applications are having multiple pages interconnected with each other. So
proper navigation system must be there which can help the end user to
successfully work through an application. There are standard methods are
available in ASP.NET 1.x that offers well defined navigation system for the web
application. Only the method which is present for building navigation within web
application is to fill the pages with hyperlinks. The drawbacks of hyperlink are
when you move pages around or change pages names.
When the site grows and new pages are added and at that time it is very difficult
for the developer to manage all links in the application. ASP.NET 2.0 and above
eliminate problems of links with a built in site navigation features. It provides
consistent way for the user to navigate the website. It enables defining all the
links at central location file as xml file and display those links in list or navigation
menus in each required page using navigation controls.

Different Navigation Controls in ASP.NET


There are three navigation controls in ASP.NET:

• SiteMapPath
• Menu Control
• TreeView
The SiteMapPath on the left shows the user the path to the current page. This
helps if users want to go up one or more levels in the site hierarchy. It also helps
them to understand where they are. The TreeView can display the structure of
your site and enables you to expand and collapse the different nodes; in Figure 7-
2 the entire tree is expanded. The Menu control on the right initially only displays
the Home menu item. However, as soon as you move the mouse over the menu item,
a submenu appears. In Figure 7-2 one of these child elements is the Reviews item,
which in turn has child elements itself.

1. SiteMapPath Control
Site maps are XML files which are mainly used to describe the logical structure of
the web application. It defines the layout of all pages in web application and how
they relate to each other. Whenever you want you can add or remove pages to
your site map there by managing navigation of website efficiently. Site map files
are defined with .sitemap extension. <sitemap> element is the root node of the
sitemap file.
It has three attributes:

• Title: It provides textual description of the link.


• URL: It provides the location of the valid physical file.
• Description: It is used for tooltip of the link.
SiteMapPath control displays the navigation path of the current page. The path
acts as click able links to previous page. The sitemap path control uses the web.
This control creates the navigation mechanism which is linear path defining where
the user is currently located in navigation arrangement. It helps end user to know
his location in relation to the rest of the site.
Properties of SiteMapPath Control:

• PathSeparator: This property is to get or set the out separator text.


• NodeStyle: This property is used to set the style of all nodes that will be
displayed.
• RootNodeStyle: This property is used to set the style on the absolute root
node.
• PathDirection: This property is used to set the direction of the links
generated in the output.
• CurrentNodeStyle: This property is used to set the style on node that
represent the current page.
• ShowToolTips: This property is used to set the tooltip for the control.
Default value is true.
• PathSeparatorStyle: This property ja used to set the style of path
separator.
2. Menu Control
Menu is an another navigation control in ASP.NET which is used to display menu in
web page. This control is used in combination with SiteMapDataSource control for
navigating the web Site. It displays two types of menu static menu and dynamic
menu. Static menu is always displayed in menu Control, by default only menu items
at the root levels are displayed. Dynamic menu is displayed only when the use
moves the mouse pointer over the parent menu that contains a dynamic sub menu.
Properties of Menu Control:

• DataSourceID: This property is used to specify the data source to be used


using sitemap file as data source.
• CssClass: This property is used to specify the CSS class attribute for the
control.
• ImgeUrl: This property is used to specify the image that appear next to the
menu item.
• Orientation: This property is used to specify the alignment of menu control.
It can be horizontal or vertical.
• Tooltip: This property is used to specify the tooltip of the menu item when
you mouse over.
• Text: This property is used to specify the text to display in the menu.
• NavigateUrl: This property is used to specify the target location to send
the user when menu item is clicked.
• Target: This property is used to specify the target page location. It can be
in new window or same window.
• Value: This property is used to specify the unique id to use in server side
events.
3. TreeView Control
TreeView is an another navigation control used in ASP.NET to display the data in
hierarchical list manner. When TreeView is displayed for the first time, it
displays all of its nodes. User can control it by setting the property called
ExpandDepth.
Properties of TreeView Control:

• DataSourceID: This property is used to specify the data source to be used


using sitemap file s data source.
• ShowLines: This property is used to specify the lines to connect the
individual item in the tree.
• CssClass: This property is used to specify the CSS class attribute for the
control.
• ExpandDepth: This property is used to specify the level at which items in
the tree are expanded.

Validation controls
ASP.Net provides various validation controls that validate the user data to ensure
that the data entered by the user are satisfied with the condition. ASP.Net
provides RequiredFieldValidator, RangeValidator, CompareValidator,
RegularExpressionValidator, CustomValidator and ValidationSummary.
RequirefFieldValidator is used when the specific filed is required, RangeValidator
is used when specific value needs to be within the specified
range, CompareValidator is used to compare the value of one control with fixed
value of another control, RegularExpressionValidator validate the input value with
the pattern of regular expression, CustomValidator allows user to create own
validation, ValidationSummary gives summary.
The BaseValidator Class
All the validation controls in ASP.Net inherit the properties and methods of the
BaseValidator class. It helps in making a generic suite of validation controls. The
important properties and methods of the BaseValidator class are:
• ControlToValidate – It indicates the input control to validate. It must be a
unique value throughout the form. This attribute is a mandatory one as it is
used to associate the input control with a validation control.
• Enabled – It enables or disables the validator.
• Text – It holds the message to be displayed in the event of a validation
failure.
• ErrorMessage – The value in this attribute is displayed either when
ValidationSummary control is used or when Text property is missing.
• IsValid – A Boolean attribute which indicates whether the control is valid or
not.
• Validate() – This method revalidates the control and updates the IsValid

Types of ASP.Net Validation Control


Following are the types of ASP.NET validation controls:
1. RequiredFieldValidator
This is an elementary validation control. Almost all the forms have some fields
that are mandatory to be filled up by the user before proceeding forward. The
Required Field Validator ensures that such fields are not left empty.
Syntax
<asp:RequiredFieldValidator ID="someUniqueId"
runat="server" ControlToValidate ="someUniqueControlId"
ErrorMessage="ErrorToDisplayOnValidationFailure"
InitialValue="aPlaceholderValue">
</asp:RequiredFieldValidator>
Notice the Initial Value attribute in the syntax above. This although acts as a
placeholder, in addition, the validation fails if the value of the field does not
change from the InitialValue on losing focus.
Note: Don’t worry much about the runat=” server” attribute. It is used to indicate
to ASP.Net that the control is available at the server side as well. Making the
control available at the server side helps in accessing the control in the code-
behind logic.
2. RangeValidator
The RangeValidator control simply specifies the permitted range within which the
input value should fall. This is most helpful for numeral input values such as age or
for Date input values.
Syntax
<asp:RangeValidator ID="some unique id"
runat="server" ControlToValidate ="someUniqueControlId"
ErrorMessage="ErrorToDisplayOnValidationFailure"
Type="Integer" MinimumValue=”0” MaximumValue=”100”>
</asp:RangeValidator>
There are three additional properties of this control

• Type – Specifies the type of data in the input field. The value is converted
to this type before validation. An exception is thrown if the value cannot be
converted to the specified type. The following data types can be compared
in RangeValidator:
o String
o Integer
o Double
o Date
o Currency
• MinimumValue – Specifies the minimum value that the field can hold.
• MaximumValue – Specifies the maximum value that the field can hold. Both
minimum and maximum values are inclusive invalidations.

3. RegularExpressionValidator

• RegularExpressions, or simply Regex, are patterns that define the format of


the text. If the text is in the same format, Regex returns true, else false.
It is recommended to read about Regex if you are not familiar with it. This
will also give you an idea about how Regex patterns are formed and how to
decipher a Regex pattern.
• Thus, a RegularExpressionValidator is a very versatile validation control. It
matches the input text against the pattern specified in the
ValidationExpression property.
Syntax
<asp:RegularExpressionValidator ID="someUniqueId"
runat="server" ControlToValidate ="someUniqueControlId"
ErrorMessage="ErrorToDisplayOnValidationFailure"
ValidationExpression=”aRegexPattern”>
</asp:RegularExpressionValidator>
An example of a Regex pattern can be ^[a-z][0-9]. This indicates that a text must
start with an alphabet and follow by a numeral.

4. CompareValidator

• The CompareValidator control compares the value of one control with either
a fixed value or a value in another control.
Syntax
<asp:CompareValidator ID="someUniqueId"
runat="server" ControlToValidate ="someUniqueControlId"
ErrorMessage="ErrorToDisplayOnValidationFailure"
Type="string" ControlToCompare=”ControlToValidateIdOfAnotherControl”
ValueToCompare=”aFixedValue” Operator=”Equal”>
</asp:CompareValidator>
There are three new properties in this validator:

• ControlToCompare – It holds the ControlToValidate Id of another form of


control. The value of both the form fields is then compared.
• ValueToCompare – A fixed value with which the comparison has to be made.
• Operator – The type of comparison. The allowed values in this attribute are:
o Equal
o NotEqual
o GreaterThan
o GreaterThanEqual
o LessThan
o LessThanEqual
o DataTypeCheck

5. CustomValidator

• ASP.Net also allows the freedom of writing your own validator. This eases
the task of a developer to validate the form at the client side itself. It also
allows putting more complex validations in place. Validations that are
business or application-specific can be written using custom validators.
• The custom validation code is written in a function in the code-behind page
and the function name is passed as an attribute to the CustomValidator
class. Custom validation can be done either at the client-side or the server-
side.
• ClientValidationFunction property specifies that the validation is to be
performed on the client-side. Such validation code must be written in some
scripting language such as JavaScript, VBScript, etc.
• The ServerValidate event handler is used when validation has to be done on
the server-side. The server-side validation routine is written in C#, VB .Net
or any other .Net language.
Syntax
<asp:CustomValidator ID="someUniqueId"
runat="server" ControlToValidate ="someUniqueControlId"
ErrorMessage="ErrorToDisplayOnValidationFailure"
ClientValidationFunction=”functionName”>
</asp:CustomValidator>

Validation groups

Validation groups allow you to validate data entry controls in groups. Server
controls such as validation controls, Button and TextBox have ValidationGroup
property that takes a string value. All the server controls having the same
ValidationGroup value act as one validation group. Validation groups come handy in
situations where you wish to validate only a small set of controls from many
controls housed on a Web Form. Using validation groups is quite easy and
straightforward. However, if you have a validation group inside a user control and
there are more than one user control instances on a Web Form you face some
problem.

Validation groups allow you to organize validation controls on a page as a set. Each
validation group can perform validation independently from other validation groups
on the page.

You create a validation group by setting the ValidationGroup property to the same
name (a string) for all the controls you want to group. You can assign any name to a
validation group, but you must use the same name for all members of the group.

During postback, the Page class's IsValid property is set based only on the
validation controls in the current validation group. The current validation group is
determined by the control that caused validation to occur. For example, if a
button control with a validation group of LoginForm is clicked, then
the IsValid property will return true if all validation controls whose
ValidationGroup property is set to LoginForm are valid. Other controls such as
a DropDownList control can also trigger validation if the
control's CausesValidation property is set to true (and the AutoPostBack property
is set to true.)

To validate programmatically, you can call the Validate method overload that takes
the validationGroup parameter to force validation for only that validation group.
Note that when you call the Validate method, the IsValid property reflects the
validity of all groups validated so far. This could include both a group that was
validated as a result of a postback, and the programmatically validated group. If
any control in either group is invalid, the IsValid property returns false.

The following code example demonstrates how to use the ValidationGroup


property to specify the controls to validate when a Button control posts back to
the server. The page contains three text boxes to capture data from the user and
three RequiredFieldValidator controls to ensure that the user does not leave a
text box blank. The RequiredFieldValidator controls for the first two text boxes
are in the PersonalInfoGroup validation group and
the RequiredFieldValidator control for the third text box is in the
LocationInfoGroup validation group. When Button1 is clicked, only the controls in
validation group PersonalInfoGroup are validated. When Button2 is clicked, only
the control in validation group LocationInfoGroup is validated

Client/Server Side Validation

Client side validation Vs server side validation

There is a usual question that which type of validations is better or best? Server
side validation or Client side Validation ?

Validations can be performed on the server side or on the client side (web browser).
The user input validation take place on the Server Side during a post back session
is called Server Side Validation and the user input validation take place on the Client
Side (web browser) is called Client Side Validation. Client Side Validation does not
require a post back. If the user request requires server resources to validate the
user input, you should use Server Side Validation. If the user request does not
require any server resources to validate the input, you can use Client Side
Validation.

Server Side Validation

In the Server Side Validation, the input submitted by the user is being sent to the
server and validated using one of server side scripting languages such as ASP.Net,
PHP etc. After the validation process on the Server Side, the feedback is sent back
to the client by a new dynamically generated web page. It is better to validate user
input on Server Side because you can protect against the malicious users, who can
easily bypass your Client Side scripting language and submit dangerous input to the
server.

Client Side Validation

In the Client Side Validation you can provide a better user experience by responding
quickly at the browser level. When you perform a Client Side Validation, all the user
inputs validated in the user's browser itself. Client Side validation does not require
a round trip to the server, so the network traffic which will help your server
perform better. This type of validation is done on the browser side using script
languages such as JavaScript, VBScript or HTML5 attributes.

For example, if the user enters an invalid email format, you can show an error
message immediately before the user move to the next field, so the user can
correct every field before they submit the form.

Mostly the Client Side Validation depends on the JavaScript Language, so if users
turn JavaScript off, it can easily bypass and submit dangerous input to the server
. So the Client Side Validation cannot protect your application from malicious
attacks on your server resources and databases.

You might also like