Professional Documents
Culture Documents
ITP213
ITP213 @2017S2
Enterprise Application Development
LECTURE 02
ASP.NET WEB SERVER CONTROL IMPLEMENTATION
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
Learning outcome
Use various list controls in web form
Use validation controls to validate data entry
Implement Code‐behind page model for ASP.NET web form
Implement event handler of web form
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
2017S2 ITP213
CheckBox and RadioButton
CheckBox and RadioButton allow user to select(checked) a true or false condition.
Property Description
Text Set the text displayed next to the check box or radio button.
Checked To determine whether check box or radio button is checked
AutoPostBack Set value to true enable automatic posting to server.
OnCheckedChanged Create a function when the checked status changed
<asp:CheckBox ID= "chkmember" Text= “Are you a member?" runat= "Server“
AutoPostBack= " true " OnCheckedChanged="CheckBox1_CheckChanged" >
</asp:CheckBox>
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
CheckBox and RadioButton
CheckedChanged event raised when someone change the CheckBox or RadioButton true or false
state.
Using CheckedChanged event to verify the CheckBox current state and perform any task when
page post to server.
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
2017S2 ITP213
List Control
List Controls provide a simple lists of option. It include ListBox, DropDownList,
CheckBoxList, RadioButtonList and BulletList.
DropDownList, RadioButtonList allow user to select only one item at a time.
ListBox, CheckBoxList allow user to select multiple items.
To work with the items in list control, you use the Items property of the
control.
Items property contains all the items of the list.
The SelectedIndexChanged event is raised when the user selects a different
item from a drop‐down list or list box.
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 5
Declare Items in List Control
Various way to add/edit items in the list control,
1. From design view
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 6
2017S2 ITP213
Source view of DropDownList Control
<asp:DropDownList ID="ddlSelectMeal" runat="server">
<asp:ListItem Value="0">‐‐Select a meal ‐‐</asp:ListItem>
<asp:ListItem Value="2.50">Chicken Sandwich</asp:ListItem>
<asp:ListItem Value="3.00">Tuna Sandwich</asp:ListItem>
<asp:ListItem Value="3.80">Beef Sandwich</asp:ListItem>
</asp:DropDownList>
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 7
Declare Items in List Control…..
2. Programmatically add items
If (region= "SE Asia“) {
ddlCountry.Items.Add("Singapore");
ddlCountry.Items.Add("Malaysia");
ddlCountry.Items.Add("Indonesia");
}
3. Bind to data source ie items are derived from database or other object
ddlCountry.DataSource = getCountry(ddlRegion.Text.ToString());
ddlCountry.DataTextField ="regionName";
ddlCountry.DataValueField="regionCode";
ddlCountry.DataBind();
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 8
2017S2 ITP213
Properties of List Control…..
Items : returns collection of list Item objects in the control
SelectedIndex: returns the index of currently selected item. If no
item is selected, the value of this property is ‐1.
Example
◦ To reset the selection in a country dropdown list
ddlCountry.SelectedIndex = ‐1;
◦ To evaluate a user selection is made
if (ddlCountry.SelectedIndex == ‐1)
lbl_error.Text = “Please select a country”;
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 9
Properties of List Control…..
SelectedValue: returns a string that contain the value of selected
item.
Example
To evaluate the selected value from a country dropdown list
if (ddlCountry.SelectedValue == “Singapore”)
theRate = 1.5;
SelectedItem : returns the item currently selected.
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 10
2017S2 ITP213
SelectedIndexChanged event
ListBox control has a SelectedIndexChanged event handler.
If AutoPostBack property is set to true, then this event is raised
whenever a new item is selected from the List control.
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountry.SelectedItem.Text==“Singapore” )
TextBoxCharge=3.25.ToString(“C”);
else
TextBoxCharge= 10.00.ToString(“C”);
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 11
Properties of List Item
Value – get or set the value associated with the list item
Price = Convert.ToDouble(ddlSelectMeal.SelectedItem.Value);
Text – get or set the text displayed of the list item
Name = ddlSelectMeal.SelectedItem.Text;
Selected – get or set the item to be selected
ddlSelectMeal.ClearSelection();
ddlSelectMeal.Items.FindByText(popularMeal).Selected = true;
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 12
2017S2 ITP213
lblSel.Text = "the selected hobby : ";
foreach(ListItem hobbyItem in cblHobby.Items)
{
if (hobbyItem.Selected == true)
lblSel.Text += hobbyItem.Value+ ", ";
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 13
Other Web Server Control
Find out more control on this link MSDN library web server control
syntax
• Panel – Container of other controls. It controls the appearance and visibility of
the controls it contains
• Calendar ‐ Displays a single‐month calendar that enables the user to select
dates
• FileUpload ‐ accepting file uploads from users
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 14
2017S2 ITP213
Validation Control
Form fields pass data that is received as a string
When data is received in the intended format, it is called valid data
Validate data become important because this data is often inserted
into databases, used by the applications.
Non validation data enable hackers to gain access to you web server
ASP.NET Validation controls assign validation rules to other form
fields.
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 15
ASP.NET Input Validation Controls
RequiredFieldValidator Makes sure a form field is not left blank.
RangeValidator Checks that a field’s value fall within a given range
CompareValidator Compares a field value with a constant value, or other field’s value.
RegularExpressionValidator Evaluates a field’s value against a pattern defined by a regular expression
such as email address. Refer to https://msdn.microsoft.com/en‐
us/library/az24scfc(v=vs.110).aspx.
CustomValidator Evaluates a field’s value using validation logic that you write yourself.
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 16
2017S2 ITP213
Quick glance of RequiredFieldValidator
https://www.youtube.com/watch?v=CXossu5pnZA
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 17
Basic properties of validator control
Members Description
ControlToValidate Indicates which input control to validate.
Display Specify the display behaviour of the error message.
None – The error message is never displayed inline. This property is used with
validation summary control to summary all error messages in one location
Static – Space for error message is reserved in the location of the validator
Dynamic‐Space for error message is dynamically added to the page
ErrorMessage When the Text property is empty, the ErrorMessage value is used as
the text that appears on the page. When the Text property is not
empty, the error message is used in the Validation Summary control.
Text It is used as the text that the validation control displays on the page.
It could be (*) to indicate error, or text like “Enter your name”
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 18
2017S2 ITP213
Basic properties of validator control (Continue)
Members Description
EnableClientScript Indicates whether client side validation will take.
Enabled Enables or disables the validator.
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.
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 19
Understanding Validation Controls
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 20
2017S2 ITP213
Understanding Validation Controls (continued)
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 21
Understanding Validation Controls (continued)
Page.isValid returns true when the controls that is being validated is valid
Default.aspx.cs
private void SubmitBtn_Click(Object Sender, EventArgs E)
{
if (Page.IsValid == true)
lblError.Text = String.Empty;
else
lblError.Text = “Correct the errors!”
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
2017S2 ITP213
Build Range Validation Controls
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 23
Building Regular Expressions
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 24
2017S2 ITP213
Build CompareValidator
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 25
CustomValidator
CustomValidator control allows developer to write application specific custom validation
routines.
It can be used for both client side and server side validation.
It has three important property
ClientValidationFunction
Specify the name of the function tot performs the client‐side validation. The function must be
written using a scripting language supported by the browser such as Javascript.
OnServerValidate
Specify the name of server side validation method. The method is written in server side
programming language such as C# or VB.
ValidateEmptyText
indicating whether empty text should be validated.
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
2017S2 ITP213
Building a Custom Client Side Validation
Drag a CustomValidator to validate
gender radio button Specify client side
validation function
<asp:CustomValidator ID="CusValidatorGender" runat="server"
ControlToValidate="rblGender" ErrorMessage="Select gender"
ForeColor="Red" Display="Static"
ClientValidationFunction="genderClientValidation"
ValidateEmptyText="True" >*
</asp:CustomValidator>
Source view of CustomValidator using client side validation
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
Javascript Client Side Validation
Write a javascript function with following syntax
◦ function ClientSideValidation(sender, args)
◦ sender is a reference to the validation control eg CusValidatorGender in previous slide.
◦ args is the object whose ‘Value’ property represents the data to be validated eg gender radio
button in previous slide
◦ The args.IsValid property determines if the data validates (true) or does not validate (false).
<script type="text/javascript">
function genderClientValidation(sender, args) {
if (args.Value == "M" || args.Value == "F") args.Value refer to the value of
the gender radio button
args.IsValid = true;
else
args.IsValid = false; args.isValid tells the validator
the result of validation.
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
2017S2 ITP213
Building a Custom Server Side Validation
Click thunder icon to
Build a specify server side
CustomValidator validation methd
to validate gender
radio button
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
ServerSide Validation
Write a server side validation in the code behind page
◦ Method _ServerValidation is created
◦ Source is a reference to the validation control eg CusValidatorGender in previous slide.
◦ args is the object represents the data to be validated eg gender radio button in previous slide
◦ The args.IsValid property determines if the data validates (true) or does not validate (false).
Default.aspx.cs
protected void Gender_ServerValidation(object source, ServerValidateEventArgs args)
{
if (rblGender.SelectedValue == "M" || rblGender.SelectedValue == "F")
args.IsValid = true;
else args.isValid tells the validator
args.IsValid = false; the result of validation.
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
2017S2 ITP213
Validation Summary Control
This control provides user with a list of errors from each individual validation
control ErrorMessage property.
https://www.youtube.com/watch?v=9sZB0EiomyE
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 31
Validate Form Data with Validation Summary
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 32
2017S2 ITP213
Sample design view with Validation Summary
A design view with 3 columns
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 33
Validate Data with Validation Summary
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 34
2017S2 ITP213
Outcome of web form with Validation Summary
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 35
A Warning on Client‐side Validation
Client‐side validation works on most modern web browser with JavaScript
enabled.
You should never rely on it as the only solution to validation because it is
easy to disable JavaScript in the browser, rendering the client‐validation
routines useless.
Malicious user can easily bypass the entire page in the browser and send
information directly to the server which cause security issue
Although client‐side validate can prevent user from sending invalid data to
the system, you should never rely on it as the only solution to validation.
ITP217 ENTERPRISE APPLICATIONS DEVELOPMENT & PROJECT COPYRIGHT © 2017 SIT 36
2017S2 ITP213
Code Behind Page
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT
Code‐behind page model for ASP.NET web form
An ASP.NET Web Forms page consists of two parts:
o Visual elements which include mark‐up, server controls, and static text.
o Programming logic which includes event handlers and other code.
Code‐behind page model offers clean separation of user interface and logic
o The mark‐up is saved in the file with extension .aspx file
o The programming code is a class file. The name of the code file varies
according to what programming language used.
Code written in C#, the code file extension is aspx.cs
Code written in vb, the code file extension is aspx.vb
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT
COPYRIGHT © 2017 SIT
2017S2 ITP213
Web form and code behind page
aspx page contains
UI for SearchProduct Expand the aspx page will
show the backend cs file
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 39
Events and Handlers
Event is an occurrence or happening such as click of a button
Event can occur at 3 levels
◦ Application – Example using session start event to count number of user visit the site.
Application event is code in Global Application class (Global.asax)
◦ Page – Example load the list of products when page is loaded in online shop
◦ Control – Example when the button is clicked, perform the calculation
Each event is bind to a handler. When an event occurs the corresponding
handler will be invoked.
Handler is a program function or method that handles an event
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 40
2017S2 ITP213
Event Handlers
Most frequently used events of controls :
Controls Event
Web Form PageLoad
Button Click
Checkbox CheckedChanged
RadioButton
DropDownList SelectedIndexChanged
RadioButtonList
ListBox
TextBox TextChanged
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 41
Create Event Handler
There are two ways to create event handler
1. In Design view, double‐click the control. The event handler is automatically named as the
id following with the event action of the control. Example double click button1 will create
an event named as button1_click
2. In Design view, select the control, in the Properties window, click the symbol, named
the event you wish.
Input the event name
instead of using default
name
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 42
2017S2 ITP213
Event Handlers
Event handlers are automatically named with format
◦ ObjectName_EventName
protected void BtnSubmit_Click(object sender, EventArgs e)
{
// write code to do something between the curly brace
}
◦ Event handler methods require two parameters:
◦ An object argument representing the raised event
◦ An EventArgs parameter used for passing data with an event
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 43
Anatomy of web page CodeBehind file
using System;
using System.Collections.Generic;
using System.Web; VS auto imports core namespaces
using System.Web.UI; to access required .NET classes
using System.Web.UI.WebControls;
Every web form is a class. It is
namespace eadLab1
derived from System.Web.UI
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) Web form class named
{ must be coded
} within the project
protected void btn1_click(object sender, EventArgs e) namespace
{
}
}
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 44
2017S2 ITP213
Page Load Event Handler
The Page_Load event handler runs EVERY time the page is loaded.
To test whether Page_Load event is FIRST time loaded, use the Page.IsPostBack
property.
If (Page.IsPostBack == false) , the page is loaded for the first time. Eg Initialise
customer detail to web from database before editing.
If it is true, the page is posted back to the server. This is caused by click a button or
selecting an item from list control
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 45
Page.isPostBack Property
isPostBack property is usually used in Page_Load event handler
When a page is first time loaded. protected void Page_Load(object sender, EventArgs e)
The SGD to USD exchange rate is retrieved {
from the server database if (Page.IsPostBack == false)
{
TextBoxSGD.Text = 1;
TextBoxUSD.Text = getRte("USD").ToString();
}
}
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 46
2017S2 ITP213
Summary
Create web page using ASP.NET controls
Use validation controls to validate form fields
Implement web form code behind logic
ENTERPRISE APPLICATIONS DEVELOPMENT PROJECT COPYRIGHT © 2017 SIT 47