Vous êtes sur la page 1sur 37

INTERNAL

Lab Guide
For
ASP.NET Web Applications and Web Services








Author(s) Ashwinee, Divya, Tirtha, Shivapriya
and Sreejith
Authorized by Dr. M.P. Ravindra
Creation/Revision Date May-2008
Version 3.0


COPYRIGHT NOTICE

All ideas and information contained in this document are the intellectual property of
Education and Research Department, Infosys Technologies Limited. This document is
not for general distribution and is meant for use only for the person they are
specifically issued to. This document shall not be loaned to anyone, within or outside
Infosys, including its customers. Copying or unauthorized distribution of this
document, in any form or means including electronic, mechanical, photocopying or
otherwise is illegal.

Education and Research Department
Infosys Technologies Limited
Electronics City
Hosur Road
Bangalore - 561 229, India.

Tel: 91 80 852 0261-270
Fax: 91 80 852 0362
www.infy.com
mailto:E&R@infy.com
Infosys Technologies Limited Document Revision History
ER/CORP/CRS/LA1010/004 Version No: 3.0 i
Document Revision History

Version Date Author(s) Reviewer(s) Comments
1.0 Jul-2005 Pushpalatha, Kiran R
K
Shyam Sundar M G FP Restructure 2005
2.0a Mar-2007 Pushpalatha, Ninad
Shinde, Lakshmi D L
Komal Papdeja,
Madhavi Pathare
FP Restructure 2007
Inclusion of User Controls
and merged Web Services
with this
2.0 May-2007 Pushpalatha, Ninad
Shinde, Lakshmi D L
Komal Papdeja,
Madhavi Pathare
Final version
3.0 Dec-2007 Ashwinee, Divya,
Tirtha, Shivapriya
and Sreejith
Lakshmi D
L,Pushpalatha
Final version
Infosys Technologies Limited Table of Contents

ER/CORP/CRS/LA1010/004 Version No.: 3.0 ii
Contents

COPYRIGHT NOTICE ....................................................................................................... I
DOCUMENT REVISION HISTORY ......................................................................................... I
CONTEXT ................................................................................................................... 3
SIMPLE ASSIGNMENT ON ASP: .............................................................................................. 3
DETAILED ASSIGNMENT ON ASP ............................................................................................ 5
ASSIGNMENT ON ASP.NET 1.1 ............................................................................................ 9
ASSIGNMENT ON ASP.NET 2.0/3.5 ..................................................................................... 10
DAY 1 ASSIGNMENTS ................................................................................................... 11
ASSIGNMENT 1: USING VISUAL STUDIO IDE TO CREATE FIRST WEB APPLICATION ......................................... 11
ASSIGNMENT 2: DESIGNING A WEB PAGE USING WEB CONTROLS .......................................................... 17
ASSIGNMENT 3: USAGE OF VALIDATION CONTROLS ....................................................................... 25
ASSIGNMENT 4: SELF ASSESSMENT ........................................................................................ 34

Infosys Technologies Limited Table of Contents

ER/CORP/CRS/LA1010/004 Version No.: 3.0 iii
Context
This document contains assignments to be completed as part of the hands on for the subject
ASP.NET 3.5 Web Applications and Web Services (Course code: LA1010)

Note: In order to complete the course, assignments in this document must be completed in the
sequence mentioned.

Simple assignment on ASP:
Objective: How to write a simple example in ASP and display in Web Page.

Problem Description: Create a simple web application.


Example 1: Open a notepad and save it as SimpleAsp.asp in C:\inetpub\wwwroot. Type the
following code in the notepad :

<html>
<body>
<%response.write(Hai, Welcome to ASP)%>
</body>
</html>


ASP code is written in between HTML code. For the WebServer to differentiate between HTML
and ASP code, the ASP code is written in between <% %>

response.write() is a method to display the contents on the web page. In this example we can
see that we are passing Hai, Welcome to ASP as input parameter which is displayed on the
web page.

Now save the file and run it in a browser with the following address

http://localhost/SimpleAsp.asp

http://localhost is a virtual path which refers to the folder c:\inetpub\wwwroot where our
webserver [IIS] is configured.

SimpleAsp.asp is the asp file which we created.

The following output is displayed

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 4 of 33


Example 2: Well see how to display current date in a web page. Open the SimpleAsp.asp that
you created in the previous example. Add the response.write() which is specified in multi
colors.

<html>
<body>
<%response.write(Hai, Welcome to ASP)%>
<br>
<%response.write(date())%>
</body>
</html>

In this example you can see that the response.write() is taking date() as an input parameter.
Now save the file and execute it. The following output will be shown.



<br> is a HTML tag which is used to put a line break

date() is a function to display current date

In the next assignment well see a detailed example in ASP and the evolution from ASP to
ASP1.1 to ASP2.0 and currently ASP3.5.
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 5 of 33

Detailed Assignment on ASP

Objective: To learn to code in ASP, understand the differences in ASP, ASP.NET 1.1, ASP.NET
2.0 and ASP.NET 3.5 and appreciate the flexibility in the newer versions. This assignment
teaches you how a dropdown list is populated using ASP.

Background:

Problem Description: Create a simple web application.

Estimated time: 20 minutes

Step 1: Create the following table and insert the following values :

<EmployeeNumber> Refers to your employee number.

create table ASP_Employee_<EmployeeNumber>
(
EmployeeId INT,
EmployeeName VARCHAR(10)
)

INSERT INTO ASP_Employee_<EmployeeNumber> VALUES(1000,'Sachin')
INSERT INTO ASP_Employee_<EmployeeNumber> VALUES(1001,'Aishwarya')
INSERT INTO ASP_Employee_<EmployeeNumber> VALUES(1002,'Manmohan')


Step 2: Open a notepad and save it as First.asp in C:\inetpub\wwwroot. Type the following
code in the notepad :

<html>
<body>
Welcome to ASP site
<br>
</body>
</html>



Step 3 : Open the Internet Explorer and type the following url in the address bar.

http://localhost/First.asp

The output is shown as below.
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 6 of 33




Step 4: Open the First.asp notepad file. Now, we will add asp code into the file. ASP code is
written in between html code and is enclosed within <% and %>. Append the code specified in
red into

<html>
<body>
Welcome to ASP site
<br>
<%
Dim strSql,strCon,objCon,objRs
%>
</body>
</html>



Note:
Dim is used to declare variables and observe that there is no datatype!!

Step 5: Create a connection object. Specify the connection string and open the connection.
Append the code in red to the First.asp file.

<html>
<body>
Welcome to ASP site
<br>

<% Dim strSql,strCon,objCon,objRs

// Specify the Connection string

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 7 of 33

strCon="Provider=SQLOLEDB.1;Password=<yourpassword>;Persist Security
Info=True;User ID=<your userid>;Initial Catalog=<your database>;Data
Source=<your datasource/Server Name>"

Set objCon=Server.CreateObject("ADODB.Connection")
objCon.ConnectionString=strCon
objCon.Open
strSql="SELECT Employeeid,EmployeeName from
ASP_Employee_<EmployeeNumber>"
%>
</body>
</html>


Step 6: In ADO.NET the data fetched from a table is stored in a DataSet [Disconnected
architecture] or read using DataReader[Connected Architecture]. In earlier versions of ASP we
did not have any of these. The only option available was the record set to store data and it did
not have as many functionalites as the DataSet/DataReader had.

Now, we'll see how to create a Recordset. Append the code in red to the First.asp file.

<html>
<body>
Welcome to ASP site
<br>

<% Dim strSql,strCon,objCon,objRs

// Specify the Connection string
strCon="Provider=SQLOLEDB.1;Password=<your
password>;Persist Security Info=True;User ID=<your userid>;Initial
Catalog=<your database>;Data Source=<your datasource>"

Set objCon=Server.CreateObject("ADODB.Connection")
objCon.ConnectionString=strCon
objCon.Open
strSql="SELECT Employeeid,EmployeeName from
ASP_Employee_<EmployeeNumber>"

// Creating RecordSet object
Set objRs=Server.CreateObject("ADODB.Recordset")

// Fetching data into recordset
objRs.Open strSql,objCon

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 8 of 33
// Traversing through the RecordSet
Do While Not objRs.EOF
Response.Write(objRs("EmployeeId"))
objRs.MoveNext
Loop
objRs.Close

%>
</body>
</html>


Note:
In C# to create a new object we use the new keyword.
Here Set keyword of VBScript is used to create an object.
Server.CreateObject is the method used to create any object
ADODB.Connection is the name of the class of which we are going to create
the object.


Step 7 : Save the changes and browse the page. Observe the following output.




Step 8 : To populate Employee Names in a DropDownList, add the following code after
objRs.Close specified in the Step 7:

objRs.Open strSql,objCon

// Creating a DropDownList
Response.Write("<select name='employee'>")

// Populating data into DropDownList

Do While Not objRs.EOF
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 9 of 33
Response.Write("<option value='" &
objRs("Employeeid") & "'>" & objRs("EmployeeName") & "</option>")
objRs.MoveNext
Loop

Response.Write("</select>")
objRs.Close


Step 9 : Save the changes and browse the page. The output is shown below :



Summary of this assignment: You have just learnt
How to create a web application in asp.
How to fetch data from database using Recordset.

Assignment on ASP.NET 1.1

Objective: To learn how dropdown list was populated in ASP.NET 1.1

Estimated Time: 15 minutes

Problem description: In the previous assignment we saw how to populate a dropdown
list using ASP. Here well see how a dropdown list was populated in ASP.NET 1.1 using a
DataSet and a DataAdapter.[Since ASP.NET 1.1 is not installed in your system, well try
it in VS2008. It is possible to do it because it is backward compatible]

Step 1: Open Visual Studio 2008, create a new web application.

Step 2: Add a dropdown list onto the form and name it drpEmployee.

Step 3: Include the following namespace if it is not available.

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 10 of 33
using System.Data;
using System.Data.SqlClient;

Step 4: Write the following code in the Page_Load event of the WebForm

SqlConnection con=new SqlConnection("user id=<your
userid>;password=<your passwd>;Database=<your DB>;Server=<your
servername>");
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter("SELECT
Employeeid,EmployeeName from ASP_Employee_<EmployeeNumber>",con);
da.Fill(ds);

drpEmployee.DataSource=ds;
drpEmployee.DataTextField="EmployeeId";
drpEmployee.DataValueField="EmployeeName";

drpEmployee.DataBind();

Step 5: Now run the application and see that the dropdown list is populated.

Summary: You have learnt how dropdown list was populated in ASP.NET 1.1

Assignment on ASP.NET 2.0/3.5

Objective: To learn how to populate a dropdown list in ASP.NET 2.0/3.5.

ASP.NET 2.0 and ASP.NET 3.5 have the similar ways of populating data into the
dropdown list. The same method as we did in ADO.NET. Follow the same method and
populate the gridview from ASP_Employee_<EmployeeNumber>.
Step 1: Create a web application using VS 2008

Step 2: Add a dropdown list to the web page.

Step 3: Using the wizard, populate the dropdown list as you did in ADO.NET.
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 11 of 33

Day 1 Assignments

Assignment 1: Using Visual Studio IDE to create first Web Application

Objective: To learn Visual Studio IDE to write a Web application and to execute it.

Background: The Microsoft Visual Studio 2008 includes a rich variety of professional tools which
help us to create Web applications easily and fast. The IDE made up of several windows that
help in editing, setting properties, executing and debugging the programs.

Problem Description: Create a simple web application.

Estimated time: 4 minutes

Step 1: Open Microsoft Visual Studio .NET 2008.



Step 2: The Microsoft VisualStudio.Net IDE opens. Now, Go to FileNewWebsite.



The following screen is displayed.

Click Here to Open
Visual Studio IDE
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 12 of 33


Step 3: Select the language as Visual C# and location as File System as shown above. Rename
the website from Website1 to FirstPage as shown in the figure above and Click OK. The
following window appears.
IMPORTANT
Name of the Website
Change to HTTP, if you want to
use a web server. [Not supported
during training].
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 13 of 33



The design environment has following parts:

Sl. No. Window Name Description
1. Web Form
This Form is used for drawing the visual interface of the
application. It contains two parts Design and Source. (The
figure above shows the Source View of Default.aspx Page).
2. Toolbox window
This window contains the icons representing various visual
objects or controls that you can place on Web form
3. Solution Explorer
This window lists all the modules present in the current
project
4. Properties Window
This window lists the properties of currently selected
object. These properties control the appearance and
behavior of the object






Step 4: You can set different properties for the WebForm


Properties window

Solution Explorer

HTML
Source View
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 14 of 33


Toolbox contains various controls (HTML, Web Form controls, Data Controls, etc.) that you can
add on the form.

Web Forms will have three views Design View and Source View and Split View. The Design
view represents the user interface and Source view represents ASP.NET syntax for the webpage.
The split view will display both design view and source view simultaneously.

Step 5: Every web form will have Code Behind page, where business logic is written. To view
Code Behind page double click on the Web Form or choose View -> Code option in the menu
bar.



Step 6: Saving the Application: Click on File and select Save Default.aspx option. It first
saves all files associated with your application in the folder you have created in the beginning.


Note:
ASP.NET 1.0/1.1 compiled everything in the solution into a DLL. This is no
longer necessary because ASP.NET 3.5 applications have a defined folder
structure. By using defined folders, code is automatically compiled.

Step 7: Go to Solution Explorer Right Click on the name of website Click on ASP.NET
Folders.
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 15 of 33
The following folders are displayed:
1. \App_Code Folder
2. \App_Data Folder
3. \App_Themes(Theme) Folder
4. \App_GlobalResources Folder
5. \App_LocalResources
6. \App_WebReferences
7. \App_Browsers




You can select any of these folders based on your requirement.
Now, let us look into the functionality of each folder.

1. \App_Code Folder: The \App_Code folder is meant to store your classes, .wsdl files, and
typed datasets. Any of these items stored in this folder are then automatically available to all
the pages within your solution. Visual Studio 2008 automatically detects this and compiles it if
it is a class (.vb or .cs), automatically creates your XML Web service proxy class (from the .wsdl
file), or automatically creates a typed dataset for you from your .xsd files. Once compiled,
these items are then instantaneously available to any of your ASP.NET pages that are in the
same solution.

2.\App_Data Folder: The \App_Data folder holds the data stores utilized by the application. It
is a good to store all the data stores your application might use centrally. The \App_Data folder
can contain Microsoft SQL Express files (.mdf files), Microsoft Access files (.mdb files), XML
files, etc..
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 16 of 33

3.\App_Themes Folder: Themes are a new way of providing a common look-and-feel to your
site across every page. You implement a theme by using a .skin file, CSS files, and images used
by the server controls of your site.

4.\App_GlobalResources Folder: Resource files are string tables that can serve as data
dictionaries for your applications when these applications require changes to content based on
things such as changes in culture. You can add Assembly Resource Files (.resx) to this folder,
and they are dynamically compiled and made part of the solution for use by all your .aspx pages
in the application. When using ASP.NET 1.0/1.1, you had to use the resgen.exe tool and also
had to compile your resource files to a .dll or .exe for use within your solution.Now it is
considerably easier to deal with resource files in ASP.NET 3.5.
In addition to strings, you can also add images and other files to your resource files.

5.\App_LocalResources: simple to incorporate resources that can be used application-wide. If
you are not interested in constructing application-wide resources,re interested in resources
that can be used for a single .aspx page only, then use \App_LocalResources folder to add
resource files that are page-specific
the name of the .resx file can be:
Default.aspx.resx
Default.aspx.fi.resx
Default.aspx.ja.resx
Default.aspx.en-gb.resx

6.\App_WebReferences:The \App_WebReferences folder is a new name for the previous Web
References folder used in previous versions of ASP.NET. Now you can use the
\App_WebReferences folder and have automatic access to the remote Web services referenced
from your application.

7.\App_Browsers:The \App_Browsers folder holds .browser files, which are XML files used to
identity the browsers making requests to the application and understanding the capabilities
these browsers have. You can find a list of globally accessible .browser files at:
\Windows\Microsoft.NET\Framework\vy.yxxxxx\CONFIG\Browsers.



Summary of this assignment: You have just learnt
How to create a web application
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 17 of 33

Assignment 2: Designing a Web page using Web controls

Objective: To understand how to design page using different controls

Problem Description:
1) To display Date and Time in Label control on Page
2) To demonstrate Page property IsPostback
3) To explore different properties of Web Controls

Estimated Time: 15 minutes

Step 1: Open the web application created in the previous assignment.

Step 2: Click on the toolbox icon (see inside circle in the toolbar) or press Ctrl+Alt+X to view
tool box as seen in the left side of the below figure.







Step 3: Change the name of the web page(Default.aspx) by right clicking on it in solution
explorer and rename it as DisplayDateTime.aspx

Step 4: Add Label control on the form. Move to properties window (or you can use the keyboard
shortcut F4) and change the property ID as lblDateTime.

Step 5: Double click on the design window to open the code window. Write the code in the
Page_Load event as mentioned below:






Step 6: To run the application Go To DebugStart Without Debugging.

Properties Window
Tool Box
Object Browser
Solution Explorer
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 18 of 33


Or Right click on the page in design view and choose View in browser.



Note:
If you Run the application for the first time, the window shown in Figure(A)
appears. Select Add a new Web.config file with debugging enabled and Click
on OK.



Figure (A)

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 19 of 33


Figure (B)




Step 7: Now from the tool box, add a button control and a label to the form.

After adding the controls, try moving the controls on the form. Its not moving!!

Problem: How to move the controls in the form?
Solution: Select the control you want to move. Go to FormatPosition.



A window shown below appears

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 20 of 33


Select the type of positioning you need.


Now try moving the control. Wow!!, thats cool. Its moving now. If you want to move other
controls, follow the same procedure.

Now set the following properties to button and label:




Now write the following code for button click event:



ID: lblDateTimeButton

ID: btnDateTime
Text: Display Date Time
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 21 of 33
Run the application and click on the button. You will see the current date and time displayed in
the label, lblDateTime.



Step 8: To Check for IsPostBack


Note: IsPostBack
This will check whether the page is loaded for the first time or not. First time
when page is loaded IsPostBack will be false. Once we click on a button,
request goes to Server, gets executed and response comes back to client. At
this time, IsPostback will be true.

Now modify the code as shown below in Page_Load event.





Note:
First time page is loaded IsPostBack is false. Label will display date and time.
Once the button is clicked IsPostBack is true, now label in Page Load will not
display date and time

Step 9: One more example to understand IsPostBack.

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 22 of 33
a) Add a new form Check_IsPostBack.aspx.
b) Add a label and a button to the form.
c) Write the following code in the Page_Load event of the form.


d) Run the application, record what the output is. Now click on the button and see the
difference in output.

Step 10: To understand Response.Write

Create a new Web Form, ResponseDemo.aspx
Drag two textbox controls, two label controls and one button on the form.
Set the properties as follows:

Control Property Value
Label1 ID lblUserName
Label1 Text User Name
Label2 ID lblDesignation
Label2 Text Designation
TextBox1 ID txtUserName
TextBox2 ID txtDesgination
Button1 ID btnSubmit
Button1 Text Submit




Write the following code for btnSubmit_Click event:

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 23 of 33


Step 10: Right click on the ResponseDemo.aspx page in the Solution Explorer and Set it as Start
Page and Run the program to see the display as shown





Note:
1) When UserName and Password are entered in appropriate textboxes
and submit button is clicked, page is submitted to server.
2) The page is executed in the server.
3) Post back event causes the pages data [Textbox data, Label data]
sent to the server.
4) When the server receives the data, it creates new instance of web
form, fills the data and processes the event that has occurred. When the
page is sent back to client, we can clearly see that data what we filled
in textboxes is retained.
(This new feature is available only in ASP.NET)

Step 11: Display Welcome message in a message box.



Step 12: Alter the above code to display the name of the user in the message box.
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 24 of 33

Step 13: Drag Checkbox control on this form.

Set the Property as follows:

Control Property Value
CheckBox1 ID chkHello

Write following code for checkbox checked changed event



Step 14: Execute the application and check the checkbox.


Note :
1) Here no event has occurred i.e. page is not sent back to server.
2) Most of the controls have a property called AutoPostBack. When an event
occurs, the page will be sent to the server if AutoPostBack=true.
3) Here in our case, the AutoPostBack was set to false and hence the event
was not fired in the server.
4) In some controls like Button, this property is set TRUE by default. But for
few controls it is false to improve performance. This property is set to TRUE
only if it is necessary.


Step 13: Now set the AutoPostBack property to true for checkbox and execute the application.

Summary of this assignment: You have learnt
Working with few web controls
IsPostBack property
AutoPostBack property
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 25 of 33

Assignment 3: Usage of Validation Controls

Objective: To understand Validation Controls in ASP.NET
Background: The validation controls check the validity of data entered in associated server
controls on the client before the page is posted back to the server. This is an important
improvement compared to previous technologies. It helps the developers to write code faster.
Problem Description: To understand the usage of validation controls.

Estimated time: 20 minutes

Required Field Validator
Step 1: Add a new Web Form and name it ValidationControls.aspx. Add the following controls



a) Do not enter anything in the textbox, now click on submit button. The page will be
submitted to the server. Now how will we make sure that the user will enter some thing
in the text box?
b) Open ToolBox, under the Validation group, add the next to the
textbox.
c) Select the required field validator, select the properties, and select the
ControlToValidate property. Select the name of the textbox you want to validate.

d) Now run the application, click on the submit button without entering anything in the
textbox. Check the output.
e) Now select the change the Enable property to False. Now
click on submit button and note the difference.
Range Validator
a) In the existing Web Form add the following controls.
ID: txtName
ID: btnSubmit
Text: Submit
ID: lblName
Text: Name
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 26 of 33



b) Add a from the tool box.
c) Set the following properties for the Range Validator



ID: txtMarks
ID: lblMarks
Text: Marks
The ID of the control you want to validate
Error message to be displayed in case of
invalid input
Datatype of the item to be validated.
The range in which you want to validate
In case of error, should the control get focus?
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 27 of 33
Compare Validator
a) Add two textbox, a button, a
Set the following properties of the Compare Validator

RegularExpression Validator
The important property for the RegularExpression validator is the validationExpression.
/d Allow a digit
/d{3} Allow only 3 digits
/d+ Allow any no. of digits
/w Allow an alpha numeric character.
/w+ Allow any no. of alpha numeric characters

Custom Validator
Refer the next assignment
Validation Summary
Set the ShowMessageBox property of Validation property to display a message box.


Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 28 of 33
Problem Description: To create a registration form.
Step 1: Create a table named members with the following structure:
Field Name Data Type
Name Varchar(25)
Age SmallInt
MailID Varchar(30)
Password Varchar(20)
UserName Varchar(20)
Step 2: Now add a new page to the application created in previous assignment. To achieve this,
in solution explorer, right click on project and select AddAdd New ItemWebForm.
Name the page as Registration.aspx.
Step 3: Next add a table on the form. To add a table onto the form, choose from menu bar,
LayoutInsertTable.
Specify number of rows as 7 and columns as 2 for the table. Change the background color (Click
on Cell Properties button).

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 29 of 33

Step 4: Place label controls in the first column and textboxes in the second column of all the
rows except the last row. In the second column of last row, place Button control. The columns
of this row must be merged because we have only one control.
To merge the cells of the last row keep the cursor in last row.
Select from menu LayoutSelectRow.
Then select Layout again from menu and click on Merge cells.

Step 5: Change the text properties of label controls, text controls and button control
appropriately (refer to the figure below). Also set the ID properties for Labels and Textboxes.




Step 6: Drag validation controls as follows, Required Field Validator below Name textbox,
Range Validator control below Age textbox, Regular expression control below EmailID textbox,
Compare Validator below ConfirmPassword textbox.
Change error message property of each validation control and give proper error messages.

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 30 of 33


Step 7: Set the properties of validation controls as follows:

Control Property Value
RequiredFieldValidator1 ID rfvName
ErrorMessage Name cannot be blank
RangeValidator1 ID rvAge
ControlToValidate txtAge
MaximumValue 60
MinimumValue 18
ErrorMessage Age must be 18 to 60
Type Integer
RegularExpression1 ID reEMailID
ControlToValidate txtEMailID
ValidationExpression InternetEMailAddress
ErrorMessage Email ID is wrong
CompareValidator1 ID cvPassword
ControlToValidate txtConfirm
ControlToCompare txtPassword
Type String
ErrorMessage Password does not match


Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 31 of 33

Step 8: To check validation write following code for button click event.



Note:
While writing the connection string, replace the ServerName, DatabaseName,
user id and password with the values that you have to use.




On successful saving of record to database, you will get the message Data is inserted
successfully.

Step 9: Now, lets validate username textbox i.e. username must contain more than 6
characters.
Drag custom validator below username textbox.
Set the following properties:
ID: cvUserName
ControlToValidate: txtUserName
ErrorMessage: User Name must be at least 6 characters



On the server side, place the validation code in the ServerValidate event procedure:

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 32 of 33




Note:
For the Custom Validator, validations can be done at Server side or Client
side. When we perform validation at server side the response to client will be
delayed. It is better to perform validation at client side. To provide client-
side validation, specify a validation script in the CustomValidator controls
ClientValidationFunction property

Step 10: To set the validation at client side we must write validation code in JavaScript. Open
Html View and write the following code in script tag. .



Step 11: Set the ClientValidationFunction property of cvUserName to CheckUserID.

Step 12: Usage of Validation Summary Control :
This control is used to display validation errors in a central location or display a general
validation error description or display lengthy error messages.
Drag this control on the form where you want error messages to be displayed. You can set
properties like DisplayMode, ShowMessageBox etc.

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 33 of 33




Note:
When you use the Validation Summary Control, all the error messages of the
other validation controls on the form will be displayed in this control. If you
want the error messages to be displayed only in the Validation Summary
Control and not on the individual validation controls on the form, set the Text
property of the validation controls to * (or any character)

Step 13: Save, compile and execute the application. Provide wrong values in the text boxes and
observe the error messages displayed

Step 14: Add a button (ID: btnCancel) to the form. Add functionality to the button such that
when clicked, all the fields are cleared.

Step 15: Execute the application and click on cancel button. What is your observation? You are
forced to enter valid data. How to overcome this?

Step 16: Set the CausesValidation property for the btnCancel button to false. Now execute the
application and check.

Summary of this assignment: You have learnt working with the following validation controls:
RequiredValidator control
RangeValidator control
RegularExpressionValidator control
CompareValidator control
CustomValidator control
Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 34 of 33

Assignment 4: Self Assessment

Problem Description: Answer the following questions. Type the answers in a file called
Day1.txt and submit

1. Start Visual Studio IDE and try to open an existing web application. [Go to File Open
and try it, do not try opening from the recent file list].
2. Add a textbox to the form, it should not allow the user to enter more than 5 chars.
3. Add a textbox, display your name in it. The textbox should allow copying the contents,
but it should not allow editing it. Try it.
4. Add a textbox, allow the user to enter the text in multiple lines.
5. Design a form as shown below.



If the user clicks on submit without entering a name, it should throw an error. When the
user clicks on hello it should display a message hello even if the text box is empty, it should
not display an error.
6. Add a Dropdown list/List box to the form; add some values to it at design time.
7. Design a form as shown below.

a. The user should be able to select only one of the radio buttons, both cannot be
selected.
b. By default Male radio button will be selected.
c. When the user clicks on display, itll display a message Male/Female based on
the selection.
8. Design a form as shown below

Infosys Technologies Limited Lab Guide for ASP.NET Web Applications & Web Services
ER/CORP/CRS/LA1010/004 Version No.: 3.0 35 of 33

a. On Page_Load the calendar should be invisible.
b. When the user clicks on >>, the calendar should be displayed.
c. When the user selects a date other than the current date, it should display an
error.
d. If the user selects the current date, it should be displayed in the textbox.
e. Hide the calendar after the current date is selected.

Vous aimerez peut-être aussi