Unit Iv
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.
-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.
A form is a section of an HTML document where you put input controls (text
boxes, check boxes, radio buttons, and pull-down lists).
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.
Controls Description
Name
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
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
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.
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.
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.
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
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.
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.
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.
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
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
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.
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
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.
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
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.
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;
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
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
End Sub
End Class
Step :3 Now Run The Program(Press F5) and Press the Click Button.
Output:
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.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
}
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:-
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
}
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:-
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 :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;
}
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;
}
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.
▪ 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 :2 Now copy the Image from computer and paste in the Website folder as
shown below:
9. ) ImageButton Control:-
It is used to display the image on Button instead of text.Properties of
ImageButton is same as Button property.
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.
• 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:
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
• 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
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:
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.
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.
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.
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.