Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
HTML and ASP.NET
1. HTML and ASP.NET
Dr. M.V. Padmavati
Professor
Bhilai Institute of Technology, Durg
M.V. Padmavati HTML and ASP.NET 1
2. Contents
Some definitions
How to create and View an HTML
document?
Basic HTML Document Format
The HTML Basic tags
ASP.NET basics
Different Controls
Database Connectivity
AJAX Controls
M.V. Padmavati HTML and ASP.NET 2
3. Definitions
HTTP – Hyper Text Transport Protocol,
layered on top of TCP
HTTPS -- secure HTTP using encryption
HTML – Hyper Text Markup Language
Web site: a collection of one or more
web pages
Home pages: first page in website
M.V. Padmavati HTML and ASP.NET 3
4. Definitions
Web Browser – Software that displays
web pages on the client side.
Example : Internet Explorer, Netscape Navigator, Mozilla Firefox, Google
chrome etc
Web server: a system on the internet
containing one or more web sites. It
should contain web server software.
Examples :Internet Information sever, Apache web server, personal web
server etc
M.V. Padmavati HTML and ASP.NET 4
5. Organization of web site
◦ Think about the sort of information (content)
you want to put on the Web.
◦ Set the goals for the Web site.
◦ Organize your content into main topics.
◦ Come up with a general structure for pages and
topics.
M.V. Padmavati HTML and ASP.NET 5
6. What is HTML?
◦ Telling the browser what to do, and what props to
use.
◦ A series of tags that are integrated into a text
document.
Tags are
◦ surrounded with angle brackets like this
<B> bold text </B> or <I> Italic text </I>.
◦ Most tags come in pairs
exceptions: <P>, <br>, <li> tags …
◦ The first tag turns the action on, and the second
turns it off.
M.V. Padmavati HTML and ASP.NET 6
7. What is HTML?
The second tag(off switch) starts with a forward
slash.
For example ,<B> text </B>
can embedded, for instance, to do this:
<HEAD><TITLE> Your text </HEAD></TITLE> it won't work.
The correct order is <HEAD><TITLE> Your text
</TITLE></HEAD>
not case sensitivity.
Many tags have attributes.
For example, <P ALIGN=CENTER> centers the paragraph following it.
Some browsers don't support the some tags and
some attributes.
M.V. Padmavati HTML and ASP.NET 7
8. HTML Page Format
<HTML>
<HEAD>
<TITLE> First Web Page</TITLE>
</HEAD>
<BODY>
<H1> Hello World </H1>
<! Rest of page goes here. This is a comment. >
</BODY>
</HTML>
M.V. Padmavati HTML and ASP.NET 8
10. Headings
<H1 ...> text </H1> -- largest of the six
<H2 ...> text </H2>
<H3 ...> text </H3>
<H4 ...> text </H4>
<H5 ...> text </H5>
<H6 ...> text </H6> -- smallest of the six
ALIGN="position" --left (default), center or right
M.V. Padmavati HTML and ASP.NET 10
11. Headings
<HTML>
<HEAD>
<TITLE>Document Headings</TITLE>
</HEAD>
<BODY>
Samples of the six heading types:
<H1>Level-1 (H1)</H1>
<H2 ALIGN="center">Level-2 (H2)</H2>
<H3><U>Level-3 (H3)</U></H3>
<H4 ALIGN="right">Level-4 (H4)</H4>
<H5>Level-5 (H5)</H5>
<H6>Level-6 (H6)</H6>
</BODY>
</HTML>
M.V. Padmavati HTML and ASP.NET 11
12. <P> Paragraph
<P> defines a paragraph
Add ALIGN="position" (left, center, right)
Multiple <P>'s do not create blank lines
Use <BR> for blank line
Fully-specified text uses <P> and </P>
But </P> is optional
M.V. Padmavati HTML and ASP.NET 12
13. <BODY>
<P>Here is some text </P>
<P ALIGN="center"> Centered text </P>
<P><P><P>
<P ALIGN="right"> Right-justified text
<! Note: no closing /P tag is not a problem>
</BODY>
M.V. Padmavati HTML and ASP.NET 13
14. <PRE> Preformatted Text
<PRE>
if (a < b) {
a++;
b = c * d;
}
else {
a--;
b = (b-1)/2;
}
</PRE>
M.V. Padmavati HTML and ASP.NET 14
15. Special Characters
Character Use
< <
> >
& &
" "
Space
M.V. Padmavati HTML and ASP.NET 15
16. Colors
Values for BGCOLOR and COLOR
◦ many are predefined (red, blue, green, ...)
◦ all colors can be specified as a six character
hexadecimal value: RRGGBB
◦ FF0000 – red
◦ 888888 – gray
◦ 004400 – dark green
◦ FFFF00 – yellow
◦ 000000-black
◦ FFFFFF-white
M.V. Padmavati HTML and ASP.NET 16
17. Fonts
<FONT COLOR="red" SIZE="2" FACE="Times Roman">
This is the text of line one </FONT>
<FONT COLOR="green" SIZE="4" FACE="Arial">
Line two contains this text </FONT>
<FONT COLOR="blue" SIZE="6" FACE="Courier"
The third line has this additional text </FONT>
Note: <FONT> is now deprecated in favor of CSS.
M.V. Padmavati HTML and ASP.NET 17
18. Ordered (Numbered) Lists
A- capital letters
<OL TYPE="1"> a- small letters
<LI> Item one </LI> i - roman numbers
<LI> Item two </LI> I- roman numbers
<OL TYPE="I" > 1- numbers
<LI> Sublist item one </LI>
<LI> Sublist item two </LI>
<OL TYPE="i">
<LI> Sub-sublist item one </LI>
<LI> Sub-sublist item two </LI>
</OL>
</OL>
</OL>
M.V. Padmavati HTML and ASP.NET 18
19. Unordered (Bulleted) Lists
<UL TYPE="disc">
<LI> One </LI>
<LI> Two </LI>
<UL TYPE="circle">
<LI> Three </LI>
<LI> Four </LI>
<UL TYPE="square">
<LI> Five </LI>
<LI> Six </LI>
</UL>
</UL>
</UL>
M.V. Padmavati HTML and ASP.NET 19
21. <A> Anchors (HyperLinks)
Link to an absolute URL:
If you get spam, contact <A
HREF="htttp:www.microsoft.com">
Microsoft </A> to report the problem.
<A HREF=FILE:D:X1.HTM>DFGFDG</A>
Link to a relative URL:
See these <A HREF="#references"> references </A>
concerning our fine products.
Link to a section within a URL:
Amazon provided a <A
HREF="www.amazon.com/#reference">
reference for our company. </A>
M.V. Padmavati HTML and ASP.NET 21
22. Naming a Section
<H2> <A NAME="#references"> Our References </A>
</H2>
To display the page in new window
M.V. Padmavati HTML and ASP.NET 22
23. Hyperlinks
<BODY>
<H3>Welcome to <A HREF="http://www.cs.virginia.edu">
<STRONG>Computer Science</STRONG></A>
at the <A HREF="www.virginia.edu">University of
Virginia.</A>
</H3>
</BODY>
M.V. Padmavati HTML and ASP.NET 23
24. Images
SRC is required
WIDTH, HEIGHT may be in units of
pixels or percentage of page or frame
◦ WIDTH="357"
◦ HEIGHT="50%"
Images scale to fit the space allowed
M.V. Padmavati HTML and ASP.NET 24
25. Images
Align=position Image/Text Placement
Left Image on left edge; text flows to right of image
Right Image on right edge; text flows to left
Top Image is left; words align with top of image
Bottom Image is left; words align with bottom of image
Middle Words align with middle of image
M.V. Padmavati HTML and ASP.NET 25
26. Images
<BODY>
<img src="dolphin.jpg" align="left" width="150" height="150"
alt="dolphin jump!">
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
This is a very cute dolphin on the left!<br>
You can see text wrap around it<br>
</BODY>
</HTML>
M.V. Padmavati HTML and ASP.NET 26
28. Tables
<TABLE> table tag
<CAPTION> optional table title
<TR> table row
<TH> table column header
<TD> table data element
M.V. Padmavati HTML and ASP.NET 28
30. <TABLE> Element Attributes
ALIGN=position -- left, center, right for table
BORDER=number -- width in pixels of border (including
any cell spacing, default 0)
CELLSPACING=number -- spacing in pixels between
cells, default about 3
CELLPADDING=number -- space in pixels between cell
border and table element, default about 1
WIDTH=number[%]-- width in pixels or percentage of
page width
M.V. Padmavati HTML and ASP.NET 30
32. <TABLE> Element Attributes
BGCOLOR=color -- background color of table,
also valid
for <TR>, <TH>, and <TD>
RULES=value -- which internal lines are
shown; values are
none, rows, cols, and all (default)
M.V. Padmavati HTML and ASP.NET 32
33. <TR> Table Row Attributes
Valid for the table row:
ALIGN -- left, center, right
VALIGN -- top, middle, bottom
BGCOLOR -- background color
<TABLE ALIGN="center" WIDTH="300" HEIGHT="200">
<TR ALIGN="left" VALIGN="top" BGCOLOR="red"><TD>One</TD><TD>Two</TD>
<TR ALIGN="center" VALIGN="middle"
BGCOLOR="lightblue"><TD>Three</TD><TD>Four</TD>
<TR ALIGN="right" VALIGN="bottom" BGCOLOR="yellow"><TD>Five</TD><TD>Six</TD>
</TABLE>
M.V. Padmavati HTML and ASP.NET 33
34. <TD> Table Cell Attributes
Valid for the table cell:
colspan -- how many columns this cell occupies
rowspan – how many rows this cell occupies
<TABLE ALIGN="center" WIDTH="300" HEIGHT="200" border="1">
<TR>
<TD colspan="1" rowspan="2">a</TD>
<TD colspan="1" rowspan="1">b</TD>
</TR>
<TR>
<TD colspan="1" rowspan="1">c</TD>
</TR>
</TABLE>
M.V. Padmavati HTML and ASP.NET 34
35. Creating Floating Frames
A floating frame, or internal frame, is
displayed as a separate box or window
within a Web page.
The frame can be placed within a Web page
in much the same way as an inline image.
M.V. Padmavati HTML and ASP.NET 35
36. The Floating Frames Syntax
The syntax for a floating frame is: <iframe src=“URL”
frameborder=“option”></iframe>
◦ URL is the name and location of the file you want to display
in the floating frame
◦ the frameborder attribute determines whether the
browser displays a border (“yes”) or not (“no”) around the
frame
◦ in addition to these attributes, you can use some of the
other attributes you used with fixed frames, such as the
marginwidth, marginheight, and name attributes
M.V. Padmavati HTML and ASP.NET 36
37. Attributes Associated
with the <iframe> Tag
Attribute Description
align="alignment" How the frame is aligned with the surrounding text (use "left" or "right" to
flow text around the inline frame.)
border="value" The size of the border around the frame, in pixels
frameborder="type" Specifies whether to display a border ("yes") or not ("no")
height="value" The height and width of the frame, in pixels
width="value"
hspace="value" The horizontal and vertical space around the frame, in pixels
vspace="value"
name="text" The name of the frame
scrolling="type" Specifies whether the frame can be scrolled ("yes") or not ("no")
src="URL" The location and filename of the page displayed in the frame
M.V. Padmavati HTML and ASP.NET 37
38. Creating a Floating Frame
<iframe width=400 height=250 align=right
hspace=5 src=“x1.htm”>
</iframe>
M.V. Padmavati HTML and ASP.NET 38
39. Viewing a Floating Frame
If you want to use
floating frames in
your Web page,
you must make
sure that your users
are running at least
Internet Explorer
3.0 or Netscape 6.2.
Users of other
browsers and
browser versions
might not be able to
view floating floatin
frames. g
frame
M.V. Padmavati HTML and ASP.NET 39
40. ASP Vs ASP.NET
ASP scripting code is usually written in languages such
as JScript or VBScript. The script-execution engine that
Active Server Pages relies on interprets code line by
line, every time the page is called.
ASP files frequently combine script code with HTML.
This results in ASP scripts that are lengthy, difficult to
read, and switch frequently between code and HTML.
We have to write script for validations.
M.V. Padmavati HTML and ASP.NET 40
41. ASP.NET
Separation of Code from HTML
To make a clean sweep, with ASP.NET you have the
ability to completely separate layout and business
logic.
We use VB.NET or C#. Using compiled languages
also means that ASP.NET pages do not suffer the
performance penalties associated with interpreted
code. ASP.NET pages are precompiled to byte-code
and Just In Time (JIT) compiled when first requested.
Provides validation controls
M.V. Padmavati HTML and ASP.NET 41
42. .NET – What Is It?
.NET Application
.NET Framework
Operating System + Hardware
M.V. Padmavati HTML and ASP.NET 42
43. Framework, Languages, And Tools
VB VC++ VC# JScript …
Common Language Specification
Visual Studio.NET
Visual Studio.NET
ASP.NET: Web Services Windows
and Web Forms Forms
ADO.NET: Data and XML
Base Class Library
Common Language Runtime
M.V. Padmavati HTML and ASP.NET 43
44. Common Language Runtime (CLR)
CLR works like a virtual machine in
executing all languages.
All .NET languages must obey the rules
and standards imposed by CLR. Examples:
◦ Object declaration, creation and use
◦ Data types, language libraries
◦ Error and exception handling
◦ Interactive Development Environment (IDE)
M.V. Padmavati HTML and ASP.NET 44
45. Multiple Language Support
• CTS is a rich type system built into the
CLR
– Implements various types (int, double, etc)
– And operations on those types
• CLS is a set of specifications that
language and library designers need to
follow
– This will ensure interoperability between
languages
M.V. Padmavati HTML and ASP.NET 45
46. Compilation in .NET
Code in another
Code in VB.NET Code in C#
.NET Language
Appropriate
VB.NET compiler C# compiler
Compiler
IL(Intermediate
Language) code
CLR
M.V. Padmavati HTML and ASP.NET 46
47. Intermediate Language (IL)
.NET languages are not compiled to machine code. They
are compiled to an Intermediate Language (IL).
CLR accepts the IL code and recompiles it to machine
code.
The code stays in memory for subsequent calls. In cases
where there is not enough memory it is discarded thus
making the process interpretive.
M.V. Padmavati HTML and ASP.NET 47
48. ASP.NET
ASP.NET ,the platform services that allow to program
Web Applications and Web Services in any .NET language
ASP.NET Uses .NET languages to generate HTML pages.
HTML page is targeted to the capabilities of the
requesting Browser
ASP.NET “Program” is compiled into a .NET class and
cached the first time it is called. All subsequent calls use
the cached version.
M.V. Padmavati HTML and ASP.NET 48
49. ASP.Net Server Controls
ServerControls represent the dynamic
elements users interact with.
Examples of server controls:
◦ HTML Controls
◦ ASP.Net Controls
◦ Validation Controls
◦ User Controls
Most server controls must reside within
a
<form runat=“server> tag
M.V. Padmavati HTML and ASP.NET 49
50. Advantages of Server Controls
HTML elements can be accessed from within code to
change their characteristics, check their values, or
dynamically update them.
ASP.Netcontrols retain their properties even after the
page was processed. This process is called the View
State.
With ASP.Net controls, developers can separate the
presentational elements and the application logic so they
can be considered separately.
M.V. Padmavati HTML and ASP.NET 50
51. What is the View State???
The persistence of data after it is sent to the server for
processing is possible because of the View State
Ifyou have created forms using HTML controls, you
have experienced the loss of data after form submission
The data is maintained in the view state by encrypting it
within a hidden form field
M.V. Padmavati HTML and ASP.NET 51
52. Looking at the View State
Look at the source code of the file after the page has been
submitted to see code similar to this…
◦ i.e. <input type= hidden”
name=“VIEWSTATE”
value=“dWtMTcy0TAy0DawNzt)PDtsPGk6Mj47Pjts
PHQ802w8aTWzPj+02wPGw5uAXJdGFaGaxk6t4=
“ />
The View State is enabled for every page by default
If you don’t intend to use the View State, set the
EnableViewState property of the Page directive to be false
◦ <%@ Page EnableViewState=“False” %>
M.V. Padmavati HTML and ASP.NET 52
53. ASP.NET overview
ASP.NET provides services to allow the creation,
deployment, and execution of Web Applications and
Web Services
Like ASP, ASP.NET is a server-side technology
Web Applications are built using Web Forms. ASP.NET
comes with built-in Web Forms controls, which are
responsible for generating the user interface. They
mirror typical HTML widgets like text boxes or
buttons.
Web Forms are designed to make building web-based
applications as easy as building Visual Basic applications
M.V. Padmavati HTML and ASP.NET 53
54. Main Data types in VB.NET
Data Type # of Bytes Values
Boolean 1 True or False
Byte 1 Unsigned
Char 2 Unicode character
Single 4 32-bit Floating Point Number
Double 8 64-bit Floating Point Number
Integer 4 32-bit Signed Integer
Long 8 64-bit Signed Integer
Short 2 16-bit Signed Integer
DateTime 8 Date and time of day
M.V. Padmavati HTML and ASP.NET 54
55. Button Controls:
ASP .Net provides three types of button controls:
◦ buttons, link buttons and image buttons.
When a user clicks a button control, two events are
raised Click and Command.
M.V. Padmavati HTML and ASP.NET 55
56. Button Properties
Property Description
The text displayed by the button. This is
Text
for button and link button controls only.
For image button control only. The image
ImageUrl
to be displayed for the button.
For image button control only. The text to
AlternateText be displayed if the browser can't display
the image.
Determines whether page validation
CausesValidation occurs when a user clicks the button. The
default is true.
The URL of the page that should be
PostBackUrl requested when the user clicks the
button.
M.V. Padmavati HTML and ASP.NET 56
57. Text Boxes and Labels
Text box controls are typically used to accept input
from the user. A text box control can accept one or
more lines to text depending upon the setting of the
TextMode attribute.
Label controls provide an easy way to display text
which can be changed from one execution of a page to
the next.
M.V. Padmavati HTML and ASP.NET 57
58. Properties of the Text Box
Property Description
Specifies the type of text box. SingleLine creates a standard text box, MultiLIne
TextMode creates a text box that accepts more than one line of text and the Password causes
the characters that are entered to be masked. The default is SingleLine.
Text The text content of the text box
MaxLength The maximum number of characters that can be entered into the text box.
It determines whether or not text wraps automatically for multi-line text box; default
Wrap
is true.
Determines whether the user can change the text in the box; default is false, i.e., the
ReadOnly
user can change the text.
The width of the text box in characters. The actual width is determined based on the
Columns
font that's used for the text entry
The height of a multi-line text box in lines. The default value is 0, means a single line
Rows
text box.
M.V. Padmavati HTML and ASP.NET 58
59. Check Boxes and Radio Buttons
A check box displays a single option that the user can
either check or uncheck and radio buttons present a
group of options from which the user can select just
one option.
To create a group of radio buttons, you specify the
same name for the GroupName attribute of each radio
button in the group. If more than one group is required
in a single form specify a different group name for each
group.
M.V. Padmavati HTML and ASP.NET 59
60. Properties of the Check Boxes and Radio Buttons
Property Description
The text displayed next to the check box or
Text
radio button.
Specifies whether it is selected or not, default
Checked
is false.
GroupName Name of the group the control belongs to.
M.V. Padmavati HTML and ASP.NET 60
61. HyperLink
Property Description
Path of the image to be displayed by
ImageUrl
the control
NavigateUrl Target link URL
Text The text to be displayed as the link
The window or frame which will
Target
load the linked page.
M.V. Padmavati HTML and ASP.NET 61
62. Image Control
Property Description
AlternateText Alternate text to be displayed
ImageAlign Alignment options for the control
Path of the image to be displayed by
ImageUrl
the control
M.V. Padmavati HTML and ASP.NET 62
63. Common Events
Event Attribute Controls
Button, image button,
Click OnClick
link button, image map
TextChanged OnTextChanged Text box
Drop-down list, list box,
SelectedIndexChanged OnSelectedIndexChanged radio button list, check
box list.
CheckedChanged OnCheckedChanged Check box, radio button
M.V. Padmavati HTML and ASP.NET 63
64. WebControls3 Example
Image control
TextBox control
DropDownList control
HyperLink control
RadioButtonList
Button control
M.V. Padmavati HTML and ASP.NET 64
65. List Controls
ASP.Net provides the controls: drop-down list, list box,
radio button list, check box list and bulleted list. These
control let a user choose from one or more items
from the list.
List boxes and drop-down list contain one or more
list items. These lists could be loaded either by code
or by the ListItem Collection Editor.
M.V. Padmavati HTML and ASP.NET 65
66. Properties of List box and Drop-down Lists
Property Description
The collection of ListItem objects that represents the items in the
Items
control. This property returns an object of type ListItemCollection.
Specifies the number of items displayed in the box. If actual list contains
Rows
more rows than displayed then a scroll bar is added.
The index of the currently selected item. If more than one item is
SelectedIndex selected, then the index of the first selected item. If no item is selected,
the value of this property is -1.
The value of the currently selected item. If more than one item is
SelectedValue selected, then the value of the first selected item. If no item is selected,
the value of this property is an empty string("").
Indicates whether a list box allows single selections or multiple selections.
SelectionMode
SelectedItem selected item
M.V. Padmavati HTML and ASP.NET 66
67. The List Item Collections
The ListItemCollection object is a collection of ListItem
objects. Each ListItem object represents one item in the
list. Items in a ListItemCollection are numbered from 0
Property Description
A ListItem object that represents the
Item(integer)
item at the specified index.
Count The number of items in the collection.
M.V. Padmavati HTML and ASP.NET 67
68. Methods of List Item Collection
Methods Description
Adds a new item to the end of the collection and assigns the string
Add(string)
parameter to the Text property of the item.
Add(ListItem) Adds a new item to the end of the collection.
Inserts an item at the specified index location in the collection, and
Insert(integer, string)
assigns the string parameter to the Text property of the item.
Insert(integer, ListItem) Inserts the item at the specified index location in the collection.
Remove(string) Removes the item with the Text value same as the string.
Remove(ListItem) Removes the specified item.
RemoveAt(integer) Removes the item at the specified index as the integer.
Clear Removes all the items of the collection.
FindByValue(string) Returns the item whose Value is same as the string.
FindByValue(Text) Returns the item whose Text is same as the string.
M.V. Padmavati HTML and ASP.NET 68
69. Common Properties of each list item objects
Property Description
Text The text displayed for the item
Selected Indicates whether the item is selected.
Value A string value associated with the item.
M.V. Padmavati HTML and ASP.NET 69
70. Radio Button list and Check Box list
A radio button list presents a list of mutually exclusive
options. A check box list presents a list of independent
options.
Property Description
This attribute specifies whether the table tags or the normal
RepeatLayout html flow to use while formatting the list when it is
rendered. The default is Table
It specifies the direction in which the controls to be
RepeatDirection repeated. The values available are Horizontal and Vertical.
Default is Vertical
It specifies the number of columns to use when repeating
RepeatColumns
the controls; default is 0.
M.V. Padmavati HTML and ASP.NET 70
71. Bulleted lists and Numbered lists
The bulleted list control creates bulleted lists or numbered lists. These
controls contain a collection of ListItem objects that could be referred
to through the Items property of the control.
Property Description
This property specifies the style and looks of the
BulletStyle
bullets, or numbers.
It specifies the URL of the image to display as bullet if
BulletImageUrl
it is set to customimage
It specifies the starting number if numbers are
FirstBulletNumber
displayed
DisplayMode Text, HyperLink or LinkButton
M.V. Padmavati HTML and ASP.NET 71
72. Bulleted lists and Numbered lists
Unlike other list controls, the bulleted list control
doesn’t have selectedItem, selectedindex and
selectedvalue properties.
If displaymode is set to Hyperlink then value
attribute specifies the navigation url.
If displaymode is set to LinkButton then the click
event is generated where index property of the e
argument is used to find the item selected by the
user.
M.V. Padmavati HTML and ASP.NET 72
73. Default Events:
Control Default Event
AdRotator AdCreated
BulletedList Click
Button Click
Calender SelectionChanged
CheckBox CheckedChanged
CheckBoxList SelectedIndexChanged
DataGrid SelectedIndexChanged
DataList SelectedIndexChanged
DropDownList SelectedIndexChanged
HyperLink Click
ImageButton Click
ImageMap Click
LinkButton Click
ListBox SelectedIndexChanged
Menu MenuItemClick
RadioButton CheckedChanged
RadioButtonList SelectedIndexChanged
M.V. Padmavati HTML and ASP.NET 73
74. The XML File
Any XML document used with an AdRotator
control— must contain one Advertisements root
element.
Within that element can be as many Ad elements as
you need. Each Ad element is similar to the following:
<Ad>
<ImageUrl>Images/france.png</ImageUrl>
<NavigateUrl>https://www.cia.gov/library/publicati
ons/
the-world-factbook/geos/fr.html
</NavigateUrl>
<AlternateText>France Information</AlternateText>
<Impressions>1</Impressions>
</Ad> M.V. Padmavati HTML and ASP.NET 74
75. AdRotator Example
Element ImageUrl specifies the path (location) of the
advertisement’s image.
Element NavigateUrl specifies the URL for the web
page that loads when a user clicks the advertisement.
The AlternateText element nested in each Ad
element contains text that displays in place of the image
when the browser cannot display the image.
The Impressions element specifies how often a
particular image appears, relative to the other images. In
our example, the advertisements display with equal
probability, because the value of each Impressions
element is set to 1.
M.V. Padmavati HTML and ASP.NET 75
76. a) b) Outline
FlagRotator.aspx
(3 of 3 )
AdRotator image
AlternateText
displayed in a tool tip
c)
Fig. | Web Form that demonstrates the AdRotator 76
M.V. Padmavati HTML and ASP.NET
web control. (Part 3 of 3. )
77. File upload control properties
Properties Description
FileName Returns the name of the file to be uploaded.
HasFile Specifies whether the control has a file to upload.
PostedFile Returns a reference to the uploaded file.
M.V. Padmavati HTML and ASP.NET 77
78. File upload control properties
The posted file is encapsulated in an object of type HttpPostedFile,
which could be accessed through the PostedFile property of the
FileUpload class.
The HttpPostedFile class has the following important properties
Properties Description
ContentLength Returns the size of the uploaded file in bytes.
FileName Returns the full filename.
M.V. Padmavati HTML and ASP.NET 78
79. File upload control properties
protected void UploadButton_Click(object sender, EventArgs e) {
if(FileUploadControl.HasFile) {
try {
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
} catch(Exception ex)
{ StatusLabel.Text = "Upload status: The file could not be uploaded. The following
error occured: " + ex.Message; }
}
M.V. Padmavati HTML and ASP.NET 79
80. Validation Controls
• To display the all errors on a page
• To check whether the user has entered correct data or not.
ASP.NET provides the following validation controls:
Required Field Validator
Range Validator
Compare Validator
Regular Expression Validator
Custom Validator
Validation Summary
M.V. Padmavati HTML and ASP.NET 80
81. The BaseValidator Class
Members Description
ControlToValidate Indicates the input control to validate.
Display Indicates how the error message is shown.
Enabled Enables or disables the validator.
ErrorMessage Error string.
Text Error text to be shown if validation fails.
IsValid Indicates whether the value of the control is valid.
SetFocusOnError It indicates whether in case of an invalid control, the focus
should switch to the related input control.
ValidationGroup The logical group of multiple validators, where this control
belongs.
Validate() This method revalidates the control and updates the IsValid
property.
M.V. Padmavati HTML and ASP.NET 81
82. 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.
•Initialvalue- to be set and if it is not
changed, the validation fails.
M.V. Padmavati HTML and ASP.NET 82
83. CompareValidator
The CompareValidator control compares a value in one
control with a fixed value or a value in another control.
Properties Description
Type it specifies the data type
ControlToCompare it specifies the value of the input control to compare with
ValueToCompare it specifies the constant value to compare with
Operator it specifies the comparison operator, the available values are:
Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,
LessThanEqual and DataTypeCheck
M.V. Padmavati HTML and ASP.NET 83
84. RangeValidator
The RangeValidator control verifies that the input value falls
within a predetermined range.
Properties Description
Type it defines the type of the data; the available values are:
Currency, Date, Double, Integer and String
MinimumValue it specifies the minimum value of the range
MaximumValue it specifies the maximum value of the range
M.V. Padmavati HTML and ASP.NET 84
85. The RegularExpressionValidator
The RegularExpressionValidator allows
validating the input text by matching against a
pattern against a regular expression. The regular
expression is set in the ValidationExpression
property.
M.V. Padmavati HTML and ASP.NET 85
86. The RegularExpressionValidator
Meta Description
characters
. Matches any character except n
[abcd] Matches any character in the set
[^abcd] Excludes any character in the set
[2-7a-mA-M] Matches any character specified in the range
w Matches any alphanumeric character and underscore
W Matches any non-word character
s Matches whitespace characters like, space, tab, new line etc.
S Matches any non-whitespace character
d Matches any decimal character
D Matches any non-decimal character
M.V. Padmavati HTML and ASP.NET 86
87. The RegularExpressionValidator
Quantifiers could be added to specify number of times a
character could appear
Quantifier Description
* Zero or more matches
+ One or more matches
? Zero or one matches
{N} N matches
{N,} N or more matches
{N,M} Between N and M matches
M.V. Padmavati HTML and ASP.NET 87
88. The ValidationSummary Control
The ValidationSummary control does not perform any validation
but shows a summary of all errors in the page.
The summary displays the values of the ErrorMessage property
of all validation controls that failed validation.
Properties Description
Displaymode Bulletlist, list or paraghaph
HeaderText The text to be displayed before the error message
showsummary True or false
Showmessagebox Display the messages in the message box
M.V. Padmavati HTML and ASP.NET 88
90. Database Connections with ASP.Net
A large number of computer applications—both desktop
and web applications—are data-driven.
These applications are largely concerned with retrieving,
displaying, and modifying data.
M.V. Padmavati HTML and ASP.NET 90
91. Database Connections with ASP.Net
The .NET Framework includes its own data access
technology, ADO.NET.
ADO. NET consists of managed classes that allow .NET
applications to connect to data sources (usually
relational databases), execute commands, and manage
disconnected data.
We will learn about ADO.NET basics such as opening a
connection, executing a SQL statement and retrieving
the results of a query.
M.V. Padmavati HTML and ASP.NET 91
92. Database Connections with ASP.Net
• ADO.NET uses a multilayered architecture
that revolves around a few key concepts, such
as Connection, Command, Reader and
DataSet objects.
• ADO.NET uses a data provider model.
M.V. Padmavati HTML and ASP.NET 92
94. Database Connections with ASP.Net
ADO.NET Data Providers
A data provider is a set of ADO.NET classes that allows you to
access a specific database, execute SQL commands, and retrieve
data.
A data provider is a bridge between your application and a data
source.
The classes that make up a data provider include the following:
• Connection: You use this object to establish a connection to a
data source.
• Command: You use this object to execute SQL commands and
stored procedures.
• DataReader: This object provides fast read-only, forward-only
access to the data retrieved from a query.
• DataAdapter: This object performs two tasks. First, you can use
it to fill a DataSet (a disconnected collection of tables and
relationships) with information extracted from a data source.
Second, you can use it to apply changes to a data source, according
to the modifications you’ve made in a DataSet.
M.V. Padmavati HTML and ASP.NET 94
95. Database Connections with ASP.Net
The .NET Framework is bundled with a small set of four
providers:
• SQL Server provider: Provides optimized access to a
SQL Server database (version 7.0 or later).
• OLE DB provider: Provides access to any data source
that has an OLE DB driver. This includes SQL Server
databases prior to version 7.0.
• ODBC provider: Provides access to any data source that
has an ODBC driver.
M.V. Padmavati HTML and ASP.NET 95
96. Database Connections with ASP.Net
• More specifically, each provider is based on the same set
of interfaces and base classes.
• For example, every Connection object implements the
IDbConnection interface, which defines core methods
such as Open() and Close().
• This standardization guarantees that every Connection
class will work in the same way and expose the same set
of core properties and methods.
M.V. Padmavati HTML and ASP.NET 96
97. Database Connections with ASP.Net
• ADO.NET also has another layer of standardization: the
DataSet.
• The DataSet is an all-purpose container for data that
you’ve retrieved from one or more tables in a data
source.
• The DataSet is completely generic—in other words,
custom providers don’t define their own custom
versions of the DataSet class.
M.V. Padmavati HTML and ASP.NET 97
98. Database Connections with ASP.Net
• Namespace Description
• System.Data.OleDb Contains the classes used to connect to an OLE DB
provider,
• including OleDbCommand, OleDbConnection, and OleDbDataAdapter. These
classes support most OLE DB providers.
• System.Data.SqlClient Contains the classes you use to connect to a Microsoft
SQL Server database, including SqlCommand, SqlConnection, and
SqlDataAdapter.
• System.Data.Odbc Contains the classes required to connect to most ODBC
drivers. These classes include OdbcCommand, OdbcConnection, and
OdbcDataAdapter. ODBC drivers are included for all kinds of data sources
and are configured through the Data Sources icon in the Control Panel.
M.V. Padmavati HTML and ASP.NET 98
99. Database Connections with ASP.Net
• The Connection Class
The Connection class allows you to establish a connection to the data
source that you want to interact with. Before you can do anything else
(including retrieving, deleting, inserting, or updating data), you need to
establish a connection.
• Connection Strings
When you create a Connection object, you need to supply a connection
string. The connection string is a series of name/value settings separated by
semicolons (;). They specify the basic information needed to create a
connection. Although connection strings vary based on the RDBMS and
provider you are using, a few pieces of information are almost always
required:
• The server where the database is located: The database server is
always located on the same computer as the ASP.NET application.
• The database you want to use: cars or myorders or …
M.V. Padmavati HTML and ASP.NET 99
100. Database Connections with ASP.Net
There’s no reason to hard-code a connection string. The
<connectionStrings> section of the web.config file is a handy place to
store your connection strings.
Here’s an example:
<connectionStrings>
<add name="stucon" connectionString="Data
Source=.SQLEXPRESS;AttachDbFilename=|
DataDirectory|student.mdf; Integrated Security=True; User
Instance=True“ providerName="System.Data.SqlClient" />
</connectionStrings>
You can then retrieve your connection string by name from the
WebConfiguration-Manager.ConnectionStrings collection, like so:
string connectionString =
WebConfigurationManager.ConnectionStrings(“stucon“).ConnectionStri
ng;
M.V. Padmavati HTML and ASP.NET 100
101. Testing a Connection
We can use the following code in the Submit button click event handler to test
// Create the Connection object.
Dim x As String = ConfigurationManager.ConnectionStrings("stucon").ToString
Dim con As SqlConnection = New SqlConnection(x)
Try
con.Open()
lblInfo.Text = "<br /><b>Connection Is:</b> " + con.State.ToString()
Catch err As Exception
lblInfo.Text = "Error reading the database. "
lblInfo.Text += err.Message
Finally
con.Close()
lblInfo.Text += "<br /><b>Now Connection Is:</b> "
lblInfo.Text += con.State.ToString()
End Try
M.V. Padmavati HTML and ASP.NET 101
102. Database Connections with ASP.Net
• Connections are a limited server resource. This means
it’s imperative that you open the connection as late as
possible and release it as quickly as possible.
• In the previous code sample, an exception handler is
used to make sure that even if an unhandled error
occurs, the connection will be closed in the finally block.
• If you don’t use this design and an unhandled exception
occurs, the connection will remain open until the
garbage collector disposes of the SqlConnection object.
M.V. Padmavati HTML and ASP.NET 102
103. Database Connections with ASP.Net
The Command Class
The Command class allows you to execute any type of
SQL statement. Although you can use a Command class
to perform data-definition tasks (such as creating and
altering databases, tables), you’re much more likely to
perform data-manipulation tasks (such as retrieving and
updating the records in a table).
M.V. Padmavati HTML and ASP.NET 103
104. Database Connections with ASP.Net
Command Basics
Before you can use a command, you need to choose the
command type, set the command text, and bind the
command to a connection.
You can perform this work by setting the corresponding
properties: CommandType, CommandText, and Connection,
or you can pass the information you need as constructor
arguments.
The command text can be a SQL statement, or the name of
a table. It all depends on the type of command you’re using.
M.V. Padmavati HTML and ASP.NET 104
105. Database Connections with ASP.Net
Value Description
CommandType.Text The command will execute a direct
SQL statement. The SQL statement is provided in the
CommandText property. This is the default value.
CommandType.TableDirect The command will query all
the records in the table. The CommandText is the name
of the table from which the command will retrieve the
records.
M.V. Padmavati HTML and ASP.NET 105
106. Database Connections with ASP.Net
For example, here’s how you would create a Command
object that represents a query:
Dim Cmd as new SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM Employees"
And here’s a more efficient way using one of the Command
constructors. Note that you don’t need to specify the
CommandType, because CommandType.Text is the default.
Dim Cmd as new SqlCommand("SELECT * FROM
Employees", con)
M.V. Padmavati HTML and ASP.NET 106
107. Database Connections with ASP.Net
• These examples simply define a Command
object; they don’t actually execute it.
• The Command object provides three methods
that you can use to perform the command,
depending on whether you want to retrieve a
full result set, retrieve a single value, or just
execute a nonquery command.
M.V. Padmavati HTML and ASP.NET 107
108. Database Connections with ASP.Net
Command Methods
Method Description
•ExecuteNonQuery() Executes non-SELECT commands, such as SQL
commands that insert, delete, or update records. The returned value
indicates the number of rows affected by the command.
•ExecuteScalar() Executes a SELECT query and returns the value of the
first field of the first row from the rowset generated by the command.
This method is usually used when executing an aggregate SELECT
command that uses functions such as COUNT() or SUM() to calculate
a single value.
•ExecuteReader() Executes a SELECT query and returns a DataReader
object that wraps a read-only, forward-only cursor.
M.V. Padmavati HTML and ASP.NET 108
109. Database Connections with ASP.Net
The DataReader Class
A DataReader allows you to read the data
returned by a SELECT command one record at a
time, in a forward-only, read-only stream.
Using a DataReader is the simplest way to get
to your data, but it lacks the sorting and relational
abilities of the disconnected DataSet. However,
the DataReader provides the quickest possible
no-nonsense access to data.
M.V. Padmavati HTML and ASP.NET 109
110. DataReader Methods
Method Description
•Read() Advances the row cursor to the next row in the stream. This
method must also be called before reading the first row of data. (When
the DataReader is first created, the row cursor is positioned just before
the first row.)
•The Read() method returns true if there’s another row to be read, or
false if it’s on the last row.
•GetValue() Returns the value stored in the field with the specified
column name or index, within the currently selected row. If you access
the field by index and inadvertently pass an invalid index that refers to a
nonexistent field, you will get an IndexOutOfRangeException
exception.
•You can also access the same value by name, which is slightly less
efficient because the DataReader must perform a lookup to find the
column with the specified name.
M.V. Padmavati HTML and ASP.NET 110
111. DataReader Methods
Method Description
GetInt32(), GetString(): These methods return the value of the field
with the specified index
GetDateTime(), in the current row, with the data type specified in the
method name.
Note that if you try to assign the returned value to a variable of the
wrong type, you’ll get an InvalidCastException exception.
Close() Closes the reader.
M.V. Padmavati HTML and ASP.NET 111
112. Database Connections with ASP.Net
The ExecuteReader() Method and the DataReader
The following example creates a simple query command to return all
the records from the Employees table in the Northwind database. The
command is created when the page is loaded.
Dim x As String =
ConfigurationManager.ConnectionStrings("stucon").ToString
Dim con As SqlConnection = New SqlConnection(x)
Dim cmd As New SqlCommand
cmd.Connection = con
cmd.CommandType = Data.CommandType.Text
cmd.CommandText = "select * from stu"
Dim reader As SqlDataReader
M.V. Padmavati HTML and ASP.NET 112
113. Try
con.Open()
reader = cmd.ExecuteReader()
lblInfo.Text = "<table border=1>"
Do While reader.Read()
If Not IsDBNull(reader.GetValue(8)) Then
lblInfo.Text &= "<tr><td>Roll Number:</td> <td>" & reader("rollno") & "</td>"
lblInfo.Text &= "<tr><td>DOB:</td> <td>" & reader.GetDateTime(8) & "</td>"
End If
Loop
lblInfo.Text &= "</table>"
reader.Close()
Catch err As Exception
-------
Finally
con.Close()
End Try
M.V. Padmavati HTML and ASP.NET 113
114. Database Connections with ASP.Net
Using Parameterized Commands
A parameterized command is simply a command that uses placeholders in
the SQL text. The placeholders indicate dynamically supplied values, which
are then sent through the Parameters collection of the Command object.
For example, this SQL statement:
SELECT * FROM stu WHERE rollno = 2
would become something like this:
SELECT * FROM stu WHERE rollno = @rollno
The placeholders are then added separately and automatically encoded.
M.V. Padmavati HTML and ASP.NET 114
115. Database Connections with ASP.Net
Consider the example shown on the next page.
In this example, the user enters a rollno, and the GridView shows all the
rows for that student.
cmd.CommandType = Data.CommandType.Text
cmd.CommandText = "select stu.rollno, name, dob , marks.sem,
marks from stu,marks where stu.rollno=@rollno"
Dim reader As SqlDataReader
con.Open()
cmd.Parameters.AddWithValue("@rollno", 2)
reader = cmd.ExecuteReader()
GridView1.DataSource = reader
GridView1.DataBind()
M.V. Padmavati HTML and ASP.NET 115
116. Data Adapter and Data Set
DataSet
DataSet is a disconnected orient architecture that means there is
no need of active connections during work with datasets and it is a
collection of DataTables and relations between tables. It is used to
hold multiple tables with data. You can select data form tables, create
views based on table and ask child rows over relations.
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database.
This dataadapter object is used to read the data from database and
bind that data to dataset. Dataadapter is a disconnected oriented
architecture.
M.V. Padmavati HTML and ASP.NET 116
117. Data Adapter and Data Set
Dim con As New SqlConnection("Data Source=xyz; Integrated
Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select * from student", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gridview1.DataSource = ds
gridview1.DataBind()
End Sub
M.V. Padmavati HTML and ASP.NET 117
119. Passing Values in ASP.Net
• A query string is information appended to the
end of a page's URL. A typical example might
look like the following:
http://localhost/test.aspx?
category=basic&price=100
• In the URL path above, the query string starts
with the question mark (?) and includes two
name-value pairs, one called "category" and the
other called "price."
M.V. Padmavati HTML and ASP.NET 119
120. Passing Values in ASP.Net
In test.aspx we will write
Request.QueryString("category").ToString
Dim x As Integer = CType(Request.QueryString(“price"),
Integer)
M.V. Padmavati HTML and ASP.NET 120
121. State Maintenance
Web (HTTP) uses a stateless protocol.
Web forms are created and destroyed each time a client
browser makes a request.
Because of this characteristic, variables declared within a Web
form do not retain their value after a page is displayed.
ASP.NET provides different mechanisms to retain data on a Web
form between requests.
To solve this problem, ASP.NET provides several ways to retain
variables' values between requests depending on the nature and
scope of the information.
M.V. Padmavati HTML and ASP.NET 121
122. State Management Recommendations
Method Use when
View state You need to store small amounts of information for a page that will
post back to itself. Use of the ViewState property provides
functionality with basic security.
Hidden fields You need to store small amounts of information for a page via a
form that will post back to itself or another page, and when
security is not an issue.
Note: You can use a hidden field only on pages that are submitted
to the server.
Cookies You need to store small amounts of information on the client when
security is not a major issue. You can store persistent data via
cookie.
Query string You are transferring small amounts of information from one page
to another via hypertext links and security is not an issue.
Note: You can use query strings only if you are requesting the
same page, or another page via a link.
M.V. Padmavati HTML and ASP.NET 122
123. ASP and Session Management
Hypertext Transfer Protocol (HTTP) is a stateless protocol. Each
browser request to a Web server is independent, and the server
retains no memory of a browser's past requests.
The Session object, one of the intrinsic objects supported by
ASPX, provides a developer with a complete Web session
management solution.
The Session object supports a dynamic associative array that a
script can use to store information. Scalar variables and object
references can be stored in the session object.
For each ASPX page requested by a user, the Session object will
preserve the information stored for the user's session. This
session information is stored in memory on the server. The user is
provided with a unique session ID that ASPX uses to match user
requests with the information specific to that user's session.
A session is terminated when you close the browser.
M.V. Padmavati HTML and ASP.NET 123
124. Session Object
Session ("UserName") = "John" ' in page1
◦ This will store the string "John" in the Session object and give it
the name "UserName."
Dim s as string=Session("UserName") ' in page2
◦ This value can be retrieved from the Session object by
referencing the Session object by name:
M.V. Padmavati HTML and ASP.NET 124
125. Store Objects as Session Variables in the
Session Object
You may want to use CType() function to cast session
variable back to an appropriate object before you use it.
In page1.asx
Dim x1 as New ClassX()
…
Session("sv_x") = x1
In page2.aspx
Dim x2 as New ClassX()
x2 = CType(Session("sv_x"), ClassX)
M.V. Padmavati HTML and ASP.NET 125
126. Using Session Objects
You can use the Session object to store information
needed for a particular user-session.
Variables stored in the Session object are not discarded
when the user jumps between pages in the application;
instead, these variables persist for the entire user-session.
The Web server automatically creates a Session object
when a Web page from the application is requested by a
user who does not already have a session.
The server destroys the Session object when the session
expires or is abandoned.
One common use for the Session object is to store user
preferences.
M.V. Padmavati HTML and ASP.NET 126
127. Variables Scope
Type Retrieval Creation Scope
URL Request.QueryStrin • Query string of targeted page
g URL
ViewState Viewstate("x") ViewState("x") = 1 Same page during
PostBack
Session Session("x") Session("x") = 1 Same visitor during
a session
M.V. Padmavati HTML and ASP.NET 127
128. AJAX Controls
AJAX stands for Asynchronous JavaScript and
XML.
This is a cross platform technology which
speeds up response time.
The AJAX server controls add script to the
page which is executed and processed by the
browser.
M.V. Padmavati HTML and ASP.NET 128
129. The Script Manager Control
The Script Manager control is the most important control
and must be present on the page for other controls to
work.
If you create an 'Ajax Enabled site' or add an 'AJAX Web
Form' from the 'Add Item' dialog box, the web form
automatically contains the script manager control. The
ScriptManager control takes care of the client-side script for
all the server side controls.
M.V. Padmavati HTML and ASP.NET 129
130. The Update Panel Control
The UpdatePanel control is a container control and derives from
the Control class. It acts as a container for the child controls
within it and does not have its own interface.
When a control inside it triggers a post back, the UpdatePanel
intervenes to initiate the post asynchronously and update just
that portion of the page.
For example, if a button control is inside the update panel and it
is clicked, only the controls within the update panel will be
affected, the controls on the other parts of the page will not be
affected. This is called the partial post back or the asynchronous
post back.
M.V. Padmavati HTML and ASP.NET 130
131. The Timer Control
The timer control is used to initiate the
post back automatically.
Placing a timer control directly inside
the UpdatePanel to act as a child control
trigger. A single timer can be the trigger
for multiple UpdatePanels.
M.V. Padmavati HTML and ASP.NET 131
132. Cookies
Cookies are small pieces of text, stored on the client's
computer to be used only by the website setting the
cookies.
This allows web applications to save information for the
user, and then re-use it on each page if needed.
The code to create and store values in a cookie
Dim etime As New HttpCookie("etime")
Dim t As New DateTime
t = Now.AddSeconds(60)
etime.Value = t
Response.Cookies.Add(etime)
M.V. Padmavati HTML and ASP.NET 132
133. Cookies
To retrieve value from a cookie
Dim etime As DateTime =
Request.Cookies("etime").Value
M.V. Padmavati HTML and ASP.NET 133
Notas do Editor
Notes: This example illustrates a common use of frames: displaying a table of contents in one frame, while showing individual pages from the site in another.
The .NET framework exposes numerous classes to the developer. These classes allow the development of rich client applications and Web based applications alike. In the above slide these classes have been divided into 4 areas. ASP.NET provides the core Web infrastructure such as Web Forms for UI based development and Web Services for programmatic interface development, User interface development on the Windows platform can be done using Windows Forms ADO.NET and XML provide the functionality for data access. Finally, the core base classes provide infrastructure services such as security, transaction management etc.