0% found this document useful (0 votes)
19 views87 pages

II Bba Web Tech (Even Sem)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views87 pages

II Bba Web Tech (Even Sem)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

AVS
COLLEGE OF ARTS & SCIENCE
(AUTONOMOUS)
Attur Main Road, Ramalingapuram, Salem - 106.
(Recognized under section 2(f) & 12(B) of UGC Act 1956 and
Accredited by NAAC with 'A' Grade)
(Co - Educational Institution | Affiliated to Periyar University, Salem
ISO 9001 : 2015 Certified Institution)
[email protected] | www.avscollege.ac.in
Ph : 9426 29322, 94427 00205.

Study Material
Paper Name : WEB TECHNOLOGY
THEORY AND PRACTICE

Paper Code : 23UBXC008


Batch : 2023-25
Semester : Even Semester
Staff In Charge : Ms. P.MERCY

1
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

SYLLABUS
UNIT - 1
Internet Basic–Introduction to HTML– List– Creating Table – linking document – frames –
graphics to HTML Doc- Creating simple static pages.
UNIT - 2
Introduction to JavaScript – Advantage of Java script – java script syntax –Data type– variable
–array –operator and expression – looping constructor – function – Dialog box.
UNIT – 3
Java Script document object model – introduction – object in HTML – event handling –
window object – browser object–form object–navigate or object–build in object–
Cookies.
UNIT – 4
ASP. NET: Language Structure – page structure – page event, properties - compiler
directives. HTML server controls – Anchor, Tables, Forms - Basic Web server controls–
label, textbox, button, image, links, check & Radio button, hyperlink.
UNIT – 5
Request and Response objects - Working with data – OLEDB connection class, Command
class Transaction class, data adaptor class, data set class. Security: Authentication, IP
Address, Secure by SSL & Client Certificates.

2
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

UNIT - 1
Internet Basic–Introduction to HTML– List– Creating Table – linking document – frames –
graphics to HTML Doc- Creating simple static pages.

Internet Basic
• The Internet is a global network that connects millions of private, public, academic,
business, and government devices.
• It allows users to access information, communicate, and share data across the world.
Internet Components
• Hardware: Physical devices such as routers, switches, and computers that make up the
Internet's infrastructure.
• Software: Programs and protocols (e.g., web browsers, email clients) that enable users
to interact with the Internet.
Types of Internet Connections
• Dial-up: An older, slower type of connection that uses telephone lines.
• Broadband: A high-speed Internet connection, typically via fiber optics, DSL, or
cable.
• Wi-Fi: Wireless Internet connection using radio waves.
• Mobile Data: Internet access through cellular networks (3G, 4G, 5G).
Internet Services
• Email: Sending and receiving electronic messages.
• World Wide Web (WWW): A collection of interconnected documents and
multimedia resources.
• File Sharing: Sharing documents, photos, and other files over the Internet.
• Social Media: Platforms like Facebook, Twitter, and Instagram for communication and
sharing content.
• Cloud Computing: Using the Internet to store and access data on remote servers
instead of local devices.
Internet Uses
• Communication: Email, video calls, instant messaging.
• Entertainment: Online streaming services, gaming, social media.
• Education: Access to online courses, research papers, and learning resources.
• Business: Online marketing, shopping, banking, and transactions.

3
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Advantages of the Internet


• Global Connectivity: Easy communication with anyone worldwide.
• Access to Information: Vast amount of data available on various topics.
• Convenience: Ability to work, study, and shop from home.
Disadvantages of the Internet
• Privacy Issues: Risk of personal information being exposed or stolen.
• Cybersecurity Threats: Vulnerability to hacking, malware, and fraud.
• Addiction: Overuse of the Internet can lead to time wastage and addiction.

Introduction to HTML
HTML stands for Hyper Text Markup Language. It is the standard language used to create
and structure content on the web.
• HTML is a markup language, not a programming language, meaning it annotates text
to define how it is structured and displayed by web browsers.
• It forms the building blocks of all websites and is complemented by CSS for style and
JavaScript for interactivity.
HTML Page Structure
The basic structure of an HTML page is shown below. It contains the essential building-block
elements (i.e. doctype declaration, HTML, head, title, and body elements) upon which all
web pages are created.

• <!DOCTYPE html> – This is the document type declaration, not a tag. It declares that
the document is an HTML5 document.
• <html> – This is called the HTML root element. All other elements are contained

4
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

within it.
• <head> – The head tag contains the “behind the scenes” elements for a webpage.
Elements within the head aren’t visible on the front end of a webpage. Typical elements
inside the <head> include:
o <title>: Defines the title displayed on the browser tab.
o <meta>: Provides information like the character set or viewport settings.
o <link>: Links external stylesheets or resources.
o <style>: Embeds internal CSS styles.
o <script>: Embeds JavaScript for functionality.
• <title> – The title is what is displayed on the top of your browser when you visit a
website and contains the title of the webpage that you are viewing.
• <h2> – The <h2> tag is a second-level heading tag.
• <p>– The <p> tag represents a paragraph of text.
• <body> – The body tag is used to enclose all the visible content of a webpage. In other
words, the body content is what the browser will show on the front end.
An HTML document can be created using an HTML text editor. Save the text file using the
“.html” or “.htm” extension. Once saved as an HTML document, the file can be opened as a
webpage in the browser.

List in HTML
A list in HTML is a way to group and organize items or elements in a specific order or
without any particular order. Lists are used to display content in a structured manner, such as
a list of items, tasks, or steps.
Types of Lists in HTML
There are three main types of lists in HTML:
1. Unordered List (ul):
o An unordered list is used to group a collection of items where the order does not
matter.
o Items in this list are displayed with bullet points.
Example:
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>

5
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

</ul>
Output:
o Apple
o Banana
o Orange
2. Ordered List (ol):
o An ordered list is used when the order of items matters (for example, steps in a
process).
o Items in this list are displayed with numbers or letters.
Example:
<ol>
<li>First Step</li>
<li>Second Step</li>
<li>Third Step</li>
</ol>
Output:
1.First Step
2.Second Step
3.Third Step

3. Description List (dl):


o A description list is used for displaying a list of terms and their corresponding
descriptions.
o It consists of two elements: <dt> (definition term) and <dd> (definition
description).
Example:
<dl>
<dt>HTML</dt>
<dd>A markup language used for creating webpages.</dd>
<dt>CSS</dt>
<dd>A stylesheet language used for designing the look and feel of a website.</dd>
</dl>
Output:
HTML: A markup language used for creating webpages.

6
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

CSS: A stylesheet language used for designing the look and feel of a website.

Creating Table in HTML


HTML Tables allow you to arrange data into rows and columns on a web page, making
it easy to display information like schedules, statistics, or other structured data in a clear format.

What is an HTML Table?


An HTML table is created using the <table> tag. Inside this tag, you use
• <tr> to define table rows,
• <th> for table headers, and
• <td> for table data cells
Each <tr> represents a row, and within each row, <th> or <td> tags represent the cells in that
row, which can contain text, images, lists, or even another table.

EXAMPLE:

<html>
<body>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Priya</td>
<td>Sharma</td>
<td>24</td>
</tr>
<tr>
<td>Arun</td>
<td>Singh</td>
<td>32</td>
</tr>

7
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

<tr>
<td>Sam</td>
<td>Watson</td>
<td>41</td>
</tr>
</table>
</body>
</html>

OUTPUT :

Linking document
• You can click on a link and jump to another document.
• When you move the mouse over a link, the mouse arrow will turn into a little hand.
HTML Links
Syntax :
The HTML <a> tag defines a hyperlink. It has the following syntax:
<a href="url">link text</a>
• The most important attribute of the <a> element is the href attribute, which indicates
the link's destination.
• The link text is the part that will be visible to the reader.
• Clicking on the link text, will send the reader to the specified URL address.
Example
This example shows how to create a link to W3Schools.com:
<a href="https://www.w3schools.com/">Visit W3Schools.com!</a>
OUTPUT:
Visit W3Schools.com!

By default, links will appear as follows in all browsers:


• An unvisited link is underlined and blue

8
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

• A visited link is underlined and purple


• An active link is underlined and red

HTML Links - The target Attribute


• By default, the linked page will be displayed in the current browser window. To change
this, you must specify another target for the link.
• The target attribute specifies where to open the linked document.
The target attribute can have one of the following values:
• _self - Default. Opens the document in the same window/tab as it was clicked
• _blank - Opens the document in a new window or tab
• _parent - Opens the document in the parent frame
• _top - Opens the document in the full body of the window

Example :
Use target="_blank" to open the linked document in a new browser window or tab:
<a href="https://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

Frames in HTML
HTML <frame> tag (Not supported in HTML5)
• HTML <frame> tag define the particular area within an HTML file where another
HTML web page can be displayed.
• A <frame> tag is used with <frameset>, and it divides a webpage into multiple
sections or frames, and each frame can contain different web pages.
Syntax
< frame src = "URL" >
Following are some specifications about the HTML <frame> tag

Display Block

Start tag/End tag Start tag(required), End tag(forbidden)

Usage Frames

9
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Example:
Create Vertical frames:
<!DOCTYPE html>
<html>
<head>
<title>Frame tag</title>
</head>
<frameset cols="25%,50%,25%">
<frame src="frame1.html" >
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>
OUTPUT:

10
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Adding Graphics to HTML Document


You can add graphics to an HTML document in several ways, mainly through images
or SVG graphics. Here's how you can include graphics:
1. Using the <img> Tag
The <img> tag is used to embed an image into the HTML document. You can specify the
image source (using the src attribute), the image's width and height, and other attributes.
Syntax:
<img src="image_source" alt="description" width="width" height="height">
• src: Specifies the path to the image (URL or relative file path).
• alt: Provides an alternative text description for the image if it cannot be displayed.
• width: Defines the width of the image (optional).
• height: Defines the height of the image (optional).
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Example</title>
</head>
<body>
<h1>Sample Image</h1>
<img src="C:\Users\mercy\OneDrive\Pictures\Screenshots\Screenshot 2024-06-07
162837.png" alt="Placeholder Image" width="150" height="150">
</body>
</html>
Output:

11
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

2. Using SVG Graphics


SVG (Scalable Vector Graphics) is a language for describing 2D graphics. You can
include SVG directly in your HTML code.
Example (Simple SVG Graphic):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SVG Example</title>
</head>
<body>
<h1>Simple SVG Circle</h1>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>
</body>
</html>
Output:

3. Using the <canvas> Tag


The <canvas> element allows you to draw graphics via JavaScript. It's mainly used for
creating interactive graphics, animations, or complex shapes.
Example (Drawing a Rectangle on Canvas):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas Example</title>

12
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

</head>
<body>
<h1>Drawing on Canvas</h1>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid
#000000;"></canvas>

<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(50, 20, 100, 50);
</script>
</body>
</html>
Output:

Creating simple static pages


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Static Page</title>
</head>
<body>
<h1>Welcome to My Static Web Page</h1>
<p>This is a simple static web page created with HTML.</p>

13
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

<h2>About Me</h2>
<p>Hello! I am learning web development, and this is my first static page.</p>

<h2>Image Example</h2>
<img src="C:\Users\mercy\OneDrive\Pictures\Screenshots\Screenshot 2024-06-07
162837.png" alt="Placeholder Image" width="300" height="200">

<h2>My Favorite Foods</h2>


<ul>
<li>Pizza</li>
<li>Burger</li>
<li>Pasta</li>
</ul>

<h2>Steps to Create a Web Page</h2>


<ol>
<li>Learn HTML basics.</li>
<li>Create a webpage using HTML tags.</li>
<li>Style your page using CSS.</li>
<li>Test and deploy your page.</li>
</ol>

<a href="https://www.example.com" target="_blank">Visit Example Website</a>


</body>
</html>

UNIT – 1
CHOOSE THE BEST ANSWER:
1. What does HTML stand for?
a) Hyperlinks and Text Markup Language
b) Hyper Text Markup Language
c) Home Tool Markup Language
d) Hyper Tool Machine Language
Answer: b) Hyper Text Markup Language

14
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

2. Which HTML tag is used to create an ordered list?


a) <ul>
b) <ol>
c) <li>
d) <dl>
Answer: b) <ol>
3. Which attribute is used to provide a hyperlink in an HTML document?
a) src
b) href
c) link
d) url
Answer: b) href
4. Which tag is used to insert an image in an HTML document?
a) <img>
b) <image>
c) <src>
d) <pic>
Answer: a) <img>
5. What is the purpose of the <frameset> tag in HTML?
a) To define a table
b) To create frames for dividing the browser window
c) To include multimedia
d) To link documents
Answer: b) To create frames for dividing the browser window
6. Which HTML tag is used to create a hyperlink?
a) <a>
b) <link>
c) <url>
d) <href>
Answer: a) <a>
7. What does the <title> tag define in an HTML document?
a) The name of the document
b) The header content
c) The title of the webpage that appears in the browser tab

15
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

d) The footer content


Answer: c) The title of the webpage that appears in the browser tab
8. Which of the following is the correct HTML tag to define an input field?
a) <input>
b) <textarea>
c) <field>
d) <form>
Answer: a) <input>
9. Which HTML tag is used to define a table row?
a) <td>
b) <th>
c) <tr>
d) <table>
Answer: c) <tr>
10. Which tag is used to create a line break in HTML?
a) <br>
b) <hr>
c) <break>
d) <line>
Answer: a) <br>
11. What is the correct HTML tag for inserting a horizontal rule?
a) <hr>
b) <rule>
c) <line>
d) <horizontal>
Answer: a) <hr>
12. What is the default value of the <ol> (ordered list) type attribute?
a) Decimal numbers
b) Roman numerals
c) Alphabetical
d) Circle
Answer: a) Decimal numbers
13. Which HTML tag is used to define a paragraph?
a) <div>

16
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

b) <p>
c) <section>
d) <header>
Answer: b) <p>
14. Which attribute is used to set the background color of a webpage in HTML?
a) bgcolor
b) color
c) background
d) style
Answer: a) bgcolor
15. How do you define a comment in HTML?
a) <!-- Comment -->
b) // Comment
c) /* Comment */
d) # Comment
Answer: a) <!-- Comment -->

Five-Mark Questions :
1. Explain the steps to create a simple HTML table.
2. Explain the basic structure of an HTML document with an example.
Ten-Mark Questions :
1. Explain the different types of lists in HTML with examples.
2. Discuss the use of frames in HTML and explain how to create a frame-based layout.
3. Explain the basic structure of an HTML document with an example.
4. Describe the process of linking documents in HTML with examples.
5. Discuss the role of graphics in HTML and explain how to add images to a webpage.

17
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

UNIT - 2
Introduction to JavaScript – Advantage of Java script – java script syntax –Data type– variable
–array –operator and expression – looping constructor – function – Dialog box.

Introduction to JavaScript
JavaScript is a versatile, dynamically typed programming language used for interactive web
applications, supporting both client-side and server-side development, and integrating
seamlessly with HTML, CSS, and a rich standard library.
• JavaScript is a single-threaded language that executes one task at a time.
• It is an Interpreted language which means it executes the code line by line.
• The data type of the variable is decided at run-time in JavaScript that’s why it is
called dynamically typed.
First Program: “Hello, World!”
A “Hello, World!” program is the simplest way to get started with any programming language.
Here’s how you can write one in JavaScript.

<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World!");
</script>
</body>
</html>

In this example
• The<script> tag is used to include JavaScript code inside an HTML document.
• console.log() prints messages to the browser’s developer console. Open the browser
console to see the “Hello, World!” message.

18
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Advantages of JavaScript
1. Client-Side Execution:
o Runs directly in the user's browser, reducing server load and speeding up
responses.
2. Easy to Learn and Use:
o Simple syntax and structure make it beginner-friendly.
3. Platform Independence:
o Compatible with all major browsers and platforms.
4. Rich Interfaces:
o Enables interactive features like drag-and-drop, sliders, and animations.
5. Versatility:
o Can be used for both front-end and back-end development (e.g., with Node.js).
6. Dynamic Updates:
o Updates content dynamically without requiring a full page reload (AJAX).
7. Extensive Libraries and Frameworks:
o Supports powerful frameworks like React, Angular, and Vue.js for faster
development.
8. Community Support:
o A vast developer community ensures abundant resources, tools, and problem-
solving forums.
9. Reduced Server Load:
o Validation and processing can be handled on the client side, minimizing server
requests.
10. Integration with Other Technologies:
o Works seamlessly with HTML and CSS to create complete web applications.

JavaScript Syntax
JavaScript syntax refers to the set of rules that define how JavaScript programs are written and
interpreted. Below are the key elements of JavaScript syntax:

1. Variables
• Variables store data values.
let x = 5; // ES6 (preferred)
var y = 10; // Older version

19
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

const z = 15; // Constant value

2. Data Types
• JavaScript supports several data types:
o Numbers: let num = 10;
o Strings: let name = "John";
o Booleans: let isActive = true;
o Objects: let person = { firstName: "John", lastName: "Doe" };
o Arrays: let fruits = ["Apple", "Banana", "Cherry"];

3. Operators
• Arithmetic: +, -, *, /, %
• Assignment: =, +=, -=, *=, /=
• Comparison: ==, ===, !=, <, >, <=, >=
• Logical: &&, ||, !

4. Comments
• Single-line: // This is a comment
• Multi-line:
/* This is a
multi-line comment */

5. Functions
• Functions are blocks of reusable code.
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice")); // Output: Hello, Alice

6. Conditionals
• Used for decision-making.
if (x > 10) {
console.log("x is greater than 10");
} else {

20
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

console.log("x is less than or equal to 10");


}

7. Loops
• Perform repetitive tasks.
for (let i = 0; i < 5; i++) {
console.log(i);
}

8. Events
• Respond to user actions.
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});

9. Objects
• Store key-value pairs.
let car = {
make: "Toyota",
model: "Camry",
year: 2021
};
console.log(car.make); // Output: Toyota

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the
data type. It can hold any type of values such as numbers, strings etc.

21
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

For example:
1. var a=40;//holding number
2. var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

represents sequence of characters e.g.


String
"hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:

Data Type Description

represents instance through which we can


Object
access members

Array represents group of similar values

RegExp represents regular expression

22
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Variable
A JavaScript variable is simply a name of storage location. The actual value of a
variable can be changed at any time. Variables are helpful in various situations such as:
o Variables as Placeholders for unknown values: They can be used in places where
the values they represent are unknown when the code is written.
o Variables as Code Clarifies: They can make the purpose of your code cleaner.
Rules of naming variables in JavaScript:
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

In JavaScript, variables are used to store data values. There are three ways to declare a variable:

1. var
• Scope: Global or function-scoped.
• Hoisting: Variables declared with var are hoisted (declared but not initialized).
• Re-declaration: Can be re-declared within the same scope.
Example:
var name = "John"; // Declare and initialize variable
console.log(name); // Output: John

2. let
• Scope: Block-scoped (only accessible within the block it is defined).
• Hoisting: Variables declared with let are hoisted, but not initialized.
• Re-declaration: Cannot be re-declared within the same scope.
Example:
let age = 25; // Declare and initialize variable
console.log(age); // Output: 25

3. const
• Scope: Block-scoped (similar to let).
• Hoisting: Variables declared with const are hoisted, but not initialized.
• Re-declaration: Cannot be re-declared within the same scope.

23
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

• Immutability: Cannot reassign the value of a const variable, though objects and arrays
declared with const can have their contents modified.
Example:
const birthYear = 1996; // Declare and initialize variable
console.log(birthYear); // Output: 1996

// This will cause an error:


birthYear = 2000; // Error: Assignment to constant variable.

Differences between var, let, and const


Feature Var let const
Scope Function/Global Block Block
Hoisting Yes (initialized as undefined) Yes (not initialized) Yes (not initialized)
Re-declaration Yes No No
Re-assignment Yes Yes No

Array in JavaScript
An array is a special variable in JavaScript used to store multiple values in a single
variable. Arrays are ordered collections of values, where each value (element) is assigned an
index.

Declaring an Array
You can declare an array in JavaScript in two ways:
1. Using Square Brackets ([])
let fruits = ["Apple", "Banana", "Cherry"];
2. Using the Array Constructor
let fruits = new Array("Apple", "Banana", "Cherry");

Accessing Array Elements


• Indexing: Array elements are accessed by their index, starting from 0 for the first
element.
Example:
let fruits = ["Apple", "Banana", "Cherry"];

24
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

console.log(fruits[0]); // Output: Apple


console.log(fruits[2]); // Output: Cherry

Array Methods
JavaScript provides various built-in methods for manipulating arrays. Some of the common
methods include:
• push(): Adds an element to the end of the array.
let fruits = ["Apple", "Banana"];
fruits.push("Cherry");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]

• pop(): Removes the last element from the array.


fruits.pop();
console.log(fruits); // Output: ["Apple", "Banana"]

• shift(): Removes the first element from the array.


fruits.shift();
console.log(fruits); // Output: ["Banana"]

• unshift(): Adds an element to the beginning of the array.


fruits.unshift("Orange");
console.log(fruits); // Output: ["Orange", "Banana"]

• length: Returns the number of elements in the array.


console.log(fruits.length); // Output: 2

• indexOf(): Returns the index of the first occurrence of a specified element.


console.log(fruits.indexOf("Banana")); // Output: 1

• splice(): Adds or removes elements from the array.


fruits.splice(1, 1, "Mango"); // Removes 1 element at index 1 and adds "Mango"
console.log(fruits); // Output: ["Orange", "Mango"]

25
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Multi-Dimensional Arrays
JavaScript arrays can also contain other arrays, creating multi-dimensional arrays
(arrays within arrays).
Example:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

console.log(matrix[0][1]); // Output: 2

Array Iteration
You can iterate through an array using loops:
for loop:
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
forEach() method:
fruits.forEach(function(fruit) {
console.log(fruit);
});

Operators and Expressions in JavaScript

1. Operators in JavaScript
Operators in JavaScript are special symbols used to perform operations on variables and values.
There are several types of operators based on their functionality.

Types of Operators
1. Arithmetic Operators
Used to perform basic arithmetic operations.
+ (Addition): Adds two values.

26
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

let sum = 5 + 3; // sum = 8


- (Subtraction): Subtracts one value from another.
let difference = 5 - 3; // difference = 2
* (Multiplication): Multiplies two values.
let product = 5 * 3; // product = 15
/ (Division): Divides one value by another.
let quotient = 6 / 3; // quotient = 2
% (Modulus): Returns the remainder of a division operation.
let remainder = 5 % 3; // remainder = 2
++ (Increment): Increases the value of a variable by 1.
let a = 5;
a++; // a = 6
-- (Decrement): Decreases the value of a variable by 1.
let b = 5;
b--; // b = 4

2. Assignment Operators
Used to assign values to variables.
=: Assigns a value to a variable.
let x = 10; // x is assigned the value 10
+=: Adds the right operand to the left operand and assigns the result to the left
operand.
let y = 5;
y += 3; // y = 8
-=: Subtracts the right operand from the left operand and assigns the result to the left
operand.
let z = 10;
z -= 4; // z = 6
*=: Multiplies the left operand by the right operand and assigns the result to the left
operand.
let p = 5;
p *= 2; // p = 10
/=: Divides the left operand by the right operand and assigns the result to the left
operand.

27
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

let q = 8;
q /= 4; // q = 2

3. Comparison Operators
Used to compare two values.
==: Equal to (value comparison).
5 == 5 // true
===: Strict equal to (value and type comparison).
5 === 5 // true
"5" === 5 // false
!=: Not equal to.
5 != 3 // true
!==: Strict not equal to (value and type comparison).
5 !== '5' // true
>: Greater than.
5 > 3 // true
<: Less than.
3 < 5 // true
>=: Greater than or equal to.
5 >= 5 // true
<=: Less than or equal to.
3 <= 5 // true

4. Logical Operators
Used to combine conditional statements.
&& (Logical AND): Returns true if both operands are true.
true && false // false
|| (Logical OR): Returns true if at least one operand is true.
true || false // true
! (Logical NOT): Reverses the logical state of its operand.
!true // false

28
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

5. Conditional (Ternary) Operator


A shorthand for an if-else statement.
let result = (5 > 3) ? "Yes" : "No"; // result = "Yes"

2. Expressions in JavaScript
An expression is a combination of variables, operators, and values that produces a result.
• Arithmetic Expression: Combines numbers and operators to perform arithmetic
operations.
let result = 5 + 3 * 2; // result = 11
• Logical Expression: Combines values with logical operators (&&, ||, !).
let isTrue = (5 > 3) && (2 < 4); // isTrue = true
• String Expression: Combines strings and operators to concatenate text.
let message = "Hello" + " " + "World"; // message = "Hello World"
• Conditional Expression: Returns a value based on a condition.
let status = (age >= 18) ? "Adult" : "Minor"; // status = "Adult"
Summary
• Operators are used to perform operations on values.
• Expressions are combinations of values, variables, and operators that evaluate to a
result.

Looping Constructs in JavaScript


Loops are used in JavaScript to perform repetitive tasks based on a condition.
JavaScript provides several looping constructs:

1. for Loop
The for loop is used to run a block of code a certain number of times, with a defined starting
point, condition, and increment/decrement step.
Syntax:
for (initialization; condition; increment) {
// code to be executed
}
Example:
for (let i = 0; i < 5; i++) {
console.log(i); // Prints numbers 0 to 4

29
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

}
• Initialization: let i = 0; initializes the loop variable.
• Condition: i < 5 is checked before every iteration. If true, the loop continues.
• Increment: i++ increases the value of i by 1 after each iteration.

2. while Loop
The while loop executes a block of code as long as the condition is true. It checks the condition
before each iteration.
Syntax:
while (condition) {
// code to be executed
}
Example:
let i = 0;
while (i < 5) {
console.log(i); // Prints numbers 0 to 4
i++; // Increment the value of i
}
• Condition: i < 5 is checked before each iteration.
• The loop continues running as long as the condition remains true.

3. do...while Loop
The do...while loop is similar to the while loop, but it checks the condition after executing the
block of code, ensuring that the code is executed at least once.
Syntax:
do {
// code to be executed
} while (condition);
Example:
let i = 0;
do {
console.log(i); // Prints numbers 0 to 4
i++;
} while (i < 5);

30
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

• The code is executed first, then the condition is checked.


• The loop runs as long as the condition is true.

4. for...in Loop
The for...in loop is used to iterate over the properties of an object (or indices of an array).
Syntax:
for (let key in object) {
// code to be executed
}
Example:
let person = { name: "Alice", age: 25, city: "New York" };
for (let key in person) {
console.log(key + ": " + person[key]); // Prints the keys and values of the object
}
• key: The variable represents the property name of the object.

5. for...of Loop
The for...of loop is used to iterate over the values in an array or other iterable objects (like
strings).
Syntax:
for (let value of iterable) {
// code to be executed
}
Example:
let arr = [10, 20, 30, 40];
for (let num of arr) {
console.log(num); // Prints 10, 20, 30, 40
}
• value: Represents each element in the array or iterable object.

Summary of Looping Constructs:


1. for loop: Best used when the number of iterations is known.
2. while loop: Useful when the number of iterations is not predetermined but depends on
a condition.

31
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

3. do...while loop: Ensures that the code inside the loop is executed at least once.
4. for...in loop: Iterates over the properties of an object.
5. for...of loop: Iterates over values in an iterable (like arrays or strings).

Function in JavaScript
A function is a block of code that performs a specific task. Functions help in organizing
code, making it reusable and easier to manage.

1. Defining a Function
Functions in JavaScript can be defined in the following way:
Syntax:
function functionName(parameters) {
// code to be executed
}
Example:
function greet(name) {
console.log("Hello, " + name);
}

greet("Alice"); // Output: Hello, Alice


• functionName: The name of the function.
• parameters: Optional values that can be passed to the function when it is called.
• Code Block: The instructions that the function will execute.

2. Function with Return Value


Functions can also return a value using the return keyword.
Syntax:
function functionName(parameters) {
return value;
}
Example:
function add(a, b) {
return a + b;
}

32
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

let result = add(5, 10);


console.log(result); // Output: 15
• return: Ends the function and sends the result back to the caller.

3. Function Expression
A function can be assigned to a variable, creating a function expression.
Syntax:
let functionName = function(parameters) {
// code to be executed
};
Example:
let square = function(x) {
return x * x;
};

console.log(square(4)); // Output: 16
• The function is now stored in the variable square.

4. Arrow Functions
Arrow functions provide a shorter syntax for writing functions. They are often used for
anonymous functions.
Syntax:
const functionName = (parameters) => {
// code to be executed
}
Example:
const multiply = (a, b) => a * b;

console.log(multiply(3, 5)); // Output: 15


• =>: The arrow signifies the function's body.
• Arrow functions are more concise and do not have their own this keyword.

5. Function Arguments

33
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Functions can take any number of arguments, and the arguments can be optional.
Example:
function sayHello(name = "Guest") {
console.log("Hello, " + name);
}

sayHello("Alice"); // Output: Hello, Alice


sayHello(); // Output: Hello, Guest
• Default parameters can be provided, so if no argument is passed, the default value is
used.

6. Anonymous Functions
Anonymous functions are functions that do not have a name. They are often used as arguments
to other functions.
Example:
setTimeout(function() {
console.log("This is an anonymous function");
}, 1000);
• setTimeout() is a JavaScript function that takes an anonymous function and a time
delay as arguments.

7. Function Scope
Functions have their own scope, meaning variables declared inside a function are not accessible
outside the function.
Example:
function testScope() {
let insideVar = "I am inside";
console.log(insideVar); // Output: I am inside
}

testScope();
console.log(insideVar); // Error: insideVar is not defined
• Variables inside a function cannot be accessed from outside.

34
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Summary of Functions:
1. Defining a function: Use the function keyword followed by a name and parameters.
2. Return values: Functions can return values using the return statement.
3. Function expression: Functions can be assigned to variables.
4. Arrow functions: A shorter syntax for defining functions.
5. Function arguments: Functions can take arguments, with optional default values.
6. Anonymous functions: Functions without a name, often used as arguments.
7. Scope: Variables declared within a function are not accessible outside it.

Dialog Boxes in JavaScript


Dialog boxes in JavaScript are used to interact with the user, either by showing information
or asking for input. There are three primary types of dialog boxes:
1. alert() – Displays a simple message to the user.
2. confirm() – Asks the user for a yes/no response.
3. prompt() – Collects input from the user.

1. alert()
The alert() method is used to display a simple message box with a message and an "OK" button.
Syntax:
alert("Message");
Example:
alert("Hello, welcome to our website!");
• Purpose: To show messages, warnings, or errors to the user.
• Behavior: The dialog box must be dismissed by clicking "OK" before continuing with
any other actions on the webpage.

2. confirm()
The confirm() method presents the user with a dialog box containing a message, along with
two buttons: "OK" (true) and "Cancel" (false). This is used to ask for user confirmation.
Syntax:
let result = confirm("Are you sure?");
Example:
let isSure = confirm("Do you want to delete this file?");
if (isSure) {

35
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

alert("File deleted.");
} else {
alert("File not deleted.");
}
• Returns: true if the user clicks "OK" and false if the user clicks "Cancel."
• Purpose: To ask for confirmation from the user before performing an action (e.g.,
deleting something).

3. prompt()
The prompt() method is used to ask the user for input. It displays a dialog box with a message
and a text input field, allowing the user to type in a response.
Syntax:
let userInput = prompt("Please enter your name:");
Example:
let name = prompt("What is your name?");
alert("Hello, " + name);
• Returns: The string the user enters. If the user clicks "Cancel," it returns null.
• Purpose: To collect input from the user.

Example of Using All Three Dialog Boxes Together:


alert("Welcome to the website!");

let confirmDelete = confirm("Do you want to delete this item?");


if (confirmDelete) {
let itemName = prompt("Enter the name of the item you want to delete:");
alert(itemName + " has been deleted.");
} else {
alert("No items were deleted.");
}

Key Differences:
1. alert(): Used for displaying information (no input).
2. confirm(): Used for asking yes/no questions.
3. prompt(): Used for getting input from the user.

36
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

These dialog boxes are useful for simple interaction with users but may interrupt the flow of
the webpage. For more complex interactions, you might consider using HTML forms or custom
modal windows.

UNIT – 2
CHOOSE THE BEST ANSWER:
1. What does HTML stand for?
a) Hyperlinks and Text Markup Language
b) Hyper Text Markup Language
c) Home Tool Markup Language
d) Hyper Tool Machine Language
Answer: b) Hyper Text Markup Language
2. Which HTML tag is used to create an ordered list?
a) a)
b) b)
c) c)
d)
Answer: b)
3. Which attribute is used to provide a hyperlink in an HTML document?
a) src
b) href
c) link
d) url
Answer: b) href
4. Which tag is used to insert an image in an HTML document?
a) a)
b) b)
c) c)
d)
Answer: a)
5. What is the purpose of the tag in HTML?
a) To define a table
b) To create frames for dividing the browser window

37
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

c) To include multimedia
d) To link documents
Answer: b) To create frames for dividing the browser window
6. What is the correct syntax to write a JavaScript variable?
a) variable x;
b) var x;
c) x variable;
d) int x;
Answer: b) var x;
7. Which data type is NOT supported in JavaScript?
a) String
b) Number
c) Boolean
d) Character
Answer: d) Character
8. Which JavaScript method is used to display a dialog box with a message and a
text box for user input?
a) alert()
b) confirm()
c) prompt()
d) message()
Answer: c) prompt()
9. What is the correct syntax to create a function in JavaScript?
a) function myFunction {}
b) function: myFunction {}
c) function myFunction() {}
d) function = myFunction()
Answer: c) function myFunction() {}
10. Which of the following is a looping construct in JavaScript?
a) if-else
b) for
c) switch
d) case
Answer: b) for

38
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

11. Which method is used to write output to the console in JavaScript?


a) log()
b) print()
c) echo()
d) console.log()
Answer: d) console.log()
12. Which symbol is used for single-line comments in JavaScript?
a) #
b) //
c) /*
d) --
Answer: b) //
13. Which operator is used for concatenating strings in JavaScript?
a) +
b) &
c) *
d) .
Answer: a) +
14. Which method is used to find the length of a string in JavaScript?
a) size()
b) length()
c) getSize()
d) length
Answer: b) length()
15. Which JavaScript keyword is used to define a constant?
a) var
b) const
c) let
d) define
Answer: b) const

39
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Five Mark Questions:


1. What are the advantages of JavaScript?
2. Explain the concept of operators and expressions in JavaScript with examples.
3. Describe the different types of loops in JavaScript and explain how they work.
4. Explain the purpose and usage of dialog boxes in JavaScript, with examples.
5. What are variables in JavaScript? Explain how to declare and use them with examples.

Ten Mark Questions:


1) Explain JavaScript syntax and data types with examples.
2) Describe JavaScript arrays and explain operations with examples.
3) Discuss JavaScript functions, their types, and provide examples.

40
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

UNIT – 3
Java Script document object model – introduction – object in HTML – event handling –
window object – browser object–form object–navigate or object–build in object–
Cookies.

JavaScript Document Object Model (DOM)


What is the DOM?
• The Document Object Model (DOM) is a programming interface for HTML and
XML documents.
• It represents the structure of a document as a tree of objects. These objects correspond
to elements in the document, such as tags, text, and attributes.
• The DOM allows JavaScript to dynamically access, modify, and interact with web
page content.
DOM Structure
• The DOM represents the document as a tree structure where:
o Document: The root of the tree.
o Elements: The HTML tags (like <div>, <p>, etc.).
o Attributes: The properties inside the tags (like id, class).
o Text: The content inside the tags.
DOM Methods
1. getElementById(): Selects an HTML element by its ID.
Syntax: document.getElementById("id")
Example:
document.getElementById("demo").innerHTML = "Hello, world!";
2. getElementsByClassName(): Selects all elements with a specified class.
Syntax: document.getElementsByClassName("class")
Example:
var elements = document.getElementsByClassName("myClass");
elements[0].innerHTML = "New Content";
3. querySelector(): Selects the first element that matches a CSS selector.
Syntax: document.querySelector("selector")
Example:
document.querySelector("#demo").innerHTML = "Selected by CSS!";
4. querySelectorAll(): Selects all elements that match a CSS selector.

41
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Syntax: document.querySelectorAll("selector")
Example:
var items = document.querySelectorAll(".item");
items.forEach(item => {
item.style.color = "blue";
});
DOM Manipulation
• Change HTML content: You can change the content of an HTML element.
document.getElementById("demo").innerHTML = "New Content!";
• Change HTML attributes: You can change attributes of elements (e.g., src of an
image).
document.getElementById("myImage").src = "newImage.jpg";
• Add/Remove elements: You can add or remove elements in the DOM.
var newDiv = document.createElement("div");
newDiv.innerHTML = "New element added!";
document.body.appendChild(newDiv);
DOM Events
The DOM allows JavaScript to interact with events (like clicks, keypresses).
Example: Adding an event listener to a button.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
Example: Using the DOM
Here’s an example of how the DOM can be used to manipulate a webpage:
HTML:
<!DOCTYPE html>
<html>
<body>
<h1 id="heading">Welcome to JavaScript DOM</h1>
<button id="changeButton">Change Text</button>
<p id="demo">This is a paragraph.</p>
</body>
</html>
JavaScript:

42
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

document.getElementById("changeButton").onclick = function() {
document.getElementById("demo").innerHTML = "Text changed!";
document.getElementById("heading").style.color = "red";
};
In this example:
• When the button is clicked, the text inside the paragraph (<p>) changes.
• The color of the heading (<h1>) changes to red.
• The DOM is a powerful tool for JavaScript to interact with and manipulate web
pages.
• By using DOM methods, you can easily modify the content, structure, and style of a
webpage in real-time.
Introduction - Objects in HTML
What are Objects in HTML?
• HTML objects are elements or parts of an HTML document that you can interact
with and manipulate using JavaScript.
• HTML elements like <div>, <p>, <input>, <form>, and <img> are treated as objects
in JavaScript, which means they have properties and methods that can be accessed
and modified.
HTML Object Model
• The HTML Object Model (HOM) is a structured representation of HTML elements
as objects.
• Each HTML element becomes an object that can be manipulated, styled, and
interacted with.
• The Document Object Model (DOM) is the actual interface that allows JavaScript to
access and control these HTML objects.
Properties of HTML Objects
HTML objects have properties that describe various aspects of the element. For example:
• innerHTML: Represents the content inside an HTML element.
• style: Contains the inline CSS styles of an element.
• value: For form elements (like <input>), it represents the current value or user input.
Example:
<p id="demo">This is a paragraph.</p>
JavaScript:
var para = document.getElementById("demo");

43
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

console.log(para.innerHTML); // Output: This is a paragraph.


Methods of HTML Objects
HTML objects also have methods that define actions to be performed. For example:
• click(): Simulates a mouse click.
• focus(): Sets focus on an element (e.g., input fields).
• blur(): Removes focus from an element.
Example:
<button id="myButton">Click Me</button>
JavaScript:
document.getElementById("myButton").click(); // Simulates clicking the button

Accessing HTML Objects Using JavaScript


In JavaScript, you can access HTML elements using various methods. Common methods
include:
• getElementById(): Access an element by its id.
• getElementsByClassName(): Access elements by their class name.
• getElementsByTagName(): Access elements by their tag name.
Example:
<div id="content">This is content.</div>

JavaScript:
var content = document.getElementById("content");
content.style.color = "blue"; // Change the text color to blue

HTML Objects and Forms


HTML form elements (like <input>, <textarea>, and <select>) are also objects. You can
manipulate their values through JavaScript.
Example:
<form>
<input type="text" id="name" value="John Doe">
<button type="button" onclick="changeName()">Change Name</button>
</form>

JavaScript:

44
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

function changeName() {
document.getElementById("name").value = "Jane Smith"; // Change the input value
}
HTML Image as an Object
Images are also treated as objects, allowing you to manipulate them using JavaScript.
Example:
<img id="myImage" src="image1.jpg" alt="Image">
<button onclick="changeImage()">Change Image</button>
JavaScript:
function changeImage() {
document.getElementById("myImage").src = "image2.jpg"; // Change image source
}

Event Handling in JavaScript


What is Event Handling?
• Event handling is the process of responding to user actions (such as clicks, keyboard
presses, mouse movements) on a webpage.
• In JavaScript, events are actions that occur in the browser, like clicking a button or
submitting a form.
• Event handling is the mechanism through which JavaScript can respond to these
actions, making webpages interactive.
Types of Events
Some common events are:
• Mouse Events: click, dblclick, mousemove, mouseover, mouseout
• Keyboard Events: keydown, keyup, keypress
• Form Events: submit, focus, blur
• Window Events: load, resize, scroll
• Touch Events: touchstart, touchend, touchmove

Event Listeners in JavaScript


To handle an event, JavaScript uses event listeners. These listeners "listen" for a
specific event and then execute a function when the event occurs.
Syntax:
element.addEventListener(event, function, useCapture);

45
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

• event: The type of event (e.g., "click", "submit").


• function: The callback function to execute when the event is triggered.
• useCapture: A Boolean value (optional) that specifies whether the event should be
captured during the capturing phase (default is false).
Example: Handling a Click Event
<button id="myButton">Click Me</button>

<script>
// Select the button element
var button = document.getElementById("myButton");

// Add an event listener for the 'click' event


button.addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
• When the user clicks the button, an alert box will show the message "Button was
clicked!".

Inline Event Handlers (Old Method)


An alternative way of handling events is by using inline event handlers directly within
HTML attributes.
Example:
<button onclick="alert('Button was clicked!')">Click Me</button>
• Here, the onclick attribute directly calls the function when the button is clicked.
Mouse Events
JavaScript can respond to various mouse actions such as clicks, mouse over, and mouse
movements.
Example: Mouse Hover Event
<p id="hoverText">Hover over me!</p>

<script>
var text = document.getElementById("hoverText");

46
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

// Change the text color when mouse is hovered over the paragraph
text.addEventListener("mouseover", function() {
text.style.color = "blue";
});

// Change the text color back when mouse leaves the paragraph
text.addEventListener("mouseout", function() {
text.style.color = "black";
});
</script>

Keyboard Events
JavaScript can handle keyboard events like key presses and key releases.
Example: Keypress Event
<input type="text" id="inputBox" placeholder="Type something...">

<script>
var input = document.getElementById("inputBox");

// Display an alert when any key is pressed inside the input box
input.addEventListener("keydown", function(event) {
alert("Key pressed: " + event.key);
});
</script>

Form Events
Form events occur when interacting with form elements like text fields, checkboxes,
and buttons.
Example: Submit Event
<form id="myForm">
<input type="text" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>

47
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

<script>
var form = document.getElementById("myForm");

// Prevent the form from submitting and show a message


form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevent default form submission
alert("Form submitted!");
});
</script>

Event Object
When an event occurs, it triggers an event object, which contains useful information
about the event.
Example: Using the Event Object
<button id="clickButton">Click Me</button>

<script>
var button = document.getElementById("clickButton");

button.addEventListener("click", function(event) {
alert("You clicked at position: X = " + event.clientX + ", Y = " + event.clientY);
});
</script>
• The event object contains properties like clientX and clientY, which tell the position
of the mouse when the event occurred.

Removing Event Listeners


You can remove an event listener if it is no longer needed using the
removeEventListener method.
Example:
<button id="removeButton">Remove Event Listener</button>

<script>
var button = document.getElementById("removeButton");

48
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

// Define the event handler function


function clickHandler() {
alert("Button clicked!");
}

// Add event listener


button.addEventListener("click", clickHandler);

// Remove event listener after 3 seconds


setTimeout(function() {
button.removeEventListener("click", clickHandler);
alert("Event listener removed.");
}, 3000);
</script>
Window Object, Browser Object, Form Object, Navigator Object, Built-in Objects in
JavaScript
1. Window Object
• Window Object represents the browser window or the environment in which the
script runs.
• It is the global object in the browser environment, meaning that all JavaScript code in
the browser has access to it.
• The window object provides methods and properties to interact with the browser
window, such as opening new windows, alerting messages, setting timeouts, etc.
Common Methods and Properties of the Window Object:
• window.alert(): Displays an alert box.
• window.confirm(): Displays a confirmation box with OK and Cancel options.
• window.prompt(): Displays a dialog box that prompts the user for input.
• window.innerWidth: Returns the inner width of the browser window.
• window.innerHeight: Returns the inner height of the browser window.
• window.setTimeout(): Executes a function after a specified time delay.
Example:
// Alert a message in the browser
window.alert("Welcome to the website!");

49
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

// Display browser window width


alert(window.innerWidth);
2. Browser Object
• The Browser Object is a part of the Window object, representing the user's browser
and its properties.
• It allows access to information about the browser, such as its name, version, and type.
Common Properties of the Browser Object:
• navigator.appName: Returns the name of the browser.
• navigator.appVersion: Returns the version of the browser.
• navigator.userAgent: Returns a string containing information about the browser.
• navigator.language: Returns the language of the browser.
Example:
// Display browser name and version
alert("Browser Name: " + navigator.appName);
alert("Browser Version: " + navigator.appVersion);
3. Form Object
• The Form Object allows interaction with HTML form elements and their data.
• It is used to access form elements such as text inputs, checkboxes, radio buttons, and
submit buttons in HTML.
Common Methods and Properties of the Form Object:
• form.elements: Returns all form elements (inputs, buttons, etc.) in an array-like
object.
• form.submit(): Submits the form.
• form.reset(): Resets all form fields to their default values.
Example:
<form id="myForm">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>

<script>
var form = document.getElementById("myForm");

50
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

form.submit(); // Submitting the form programmatically


</script>
4. Navigator Object
• The Navigator Object is a property of the window object and provides information
about the browser, device, and user’s environment.
• It allows you to detect the browser, platform, and other details like the user’s language
and online status.
Common Properties of the Navigator Object:
• navigator.onLine: Returns true if the user is online, otherwise false.
• navigator.language: Returns the default language of the browser.
• navigator.platform: Returns the platform (operating system) of the user's device.
Example:
// Check if the user is online
if (navigator.onLine) {
alert("You are online!");
} else {
alert("You are offline.");
}

// Display user's default language


alert("Your default language is: " + navigator.language);
5. Built-in Objects
• Built-in Objects in JavaScript are objects provided by the language that have useful
methods and properties.
• Some commonly used built-in objects are:
o String: Used for manipulating text.
o Array: Used for storing ordered collections of data.
o Math: Provides mathematical constants and functions.
o Date: Used for working with dates and times.
o RegExp: Used for regular expressions.
Examples of Built-in Objects:
• String Object:
var str = "Hello, World!";
alert(str.length); // Returns the length of the string

51
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

• Math Object:
alert(Math.random()); // Returns a random number between 0 and 1
• Date Object:
var currentDate = new Date();
alert(currentDate); // Displays current date and time
NOTES:
• Window Object: Represents the browser window and provides methods for
interacting with the window.
• Browser Object: Provides information about the browser’s environment, such as
browser name, version, and language.
• Form Object: Represents HTML forms and provides methods to manipulate form
elements and submit the form.
• Navigator Object: Provides information about the browser, device, and user
environment (e.g., online status, language, platform).
• Built-in Objects: Include objects like String, Array, Math, Date, and RegExp that
help perform various common operations in JavaScript.

Cookies in JavaScript
Introduction to Cookies
• Cookies are small text files that are stored on the user's device (browser) when they
visit a website.
• They help in storing information that can be retrieved and sent back to the server
during subsequent requests.
• Cookies can store data like user preferences, session information, and more.
Why Cookies Are Used
• Session Management: To store user login status or other session-related data.
• User Preferences: Storing user-selected settings like theme, language, etc.
• Tracking: Cookies can track user activity on a website, for example, for analytics or
advertisements.
Creating Cookies in JavaScript
Cookies are created by assigning a string to the document.cookie property.
Syntax:
document.cookie = "key=value; expires=date; path=path; domain=domain; secure";
• key=value: The name and value of the cookie.

52
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

• expires=date: Specifies when the cookie will expire. If not set, it becomes a session
cookie (deleted when the browser closes).
• path: Specifies the URL path where the cookie is accessible.
• domain: Specifies the domain for which the cookie is valid.
• secure: Ensures the cookie is only sent over HTTPS connections.
Example:
document.cookie = "username=JohnDoe; expires=Thu, 18 Jan 2025 12:00:00 UTC; path=/";
Reading Cookies
You can read cookies using document.cookie. It returns all cookies in a single string.
Example:
var cookies = document.cookie;
console.log(cookies); // Output: "username=JohnDoe; theme=dark"
Accessing Specific Cookies
Since document.cookie returns all cookies in one string, you need to parse it to extract a
specific cookie.
Example:
function getCookie(name) {
var cookieArr = document.cookie.split(";");
for (var i = 0; i < cookieArr.length; i++) {
var cookie = cookieArr[i].trim();
if (cookie.indexOf(name + "=") === 0) {
return cookie.substring(name.length + 1);
}
}
return null;
}

var username = getCookie("username");


console.log(username); // Output: JohnDoe
Updating Cookies
To update a cookie, assign a new value to the cookie with the same name. You can also
update the expires date if needed.
Example:
document.cookie = "username=JaneDoe; expires=Thu, 18 Jan 2025 12:00:00 UTC; path=/";

53
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Deleting Cookies
To delete a cookie, set its expires attribute to a past date.
Example:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
Security and Limitations of Cookies
• Size Limit: Cookies are limited to around 4 KB of data.
• Security: If not handled properly, cookies can be vulnerable to security risks like theft
or manipulation. Use the secure attribute to ensure cookies are only sent over HTTPS
connections.
• Privacy: Be cautious when using cookies to track user behavior. Always follow
privacy guidelines and inform users.
Common Use Cases for Cookies
1. Login Sessions: Storing user authentication information.
2. User Preferences: Storing settings like theme or language.
3. Tracking and Analytics: Storing user activity for analytics purposes.
NOTE:
• Cookies are small pieces of data that help in storing user-specific information in the
browser.
• In JavaScript, you can create, read, update, and delete cookies using document.cookie.
• While cookies are useful for many purposes like session management and
personalization, it is important to handle them securely and responsibly.

54
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

UNIT – 3
CHOOSE THE BEST ANSWER:
What is used to store small pieces of data in a user's browser?
a) Cookies
b) Local Storage
c) Session Storage
d) Cache
Answer: a) Cookies
Which method allows you to access an element by its ID in JavaScript?
a) getElementById()
b) querySelector()
c) getElementsByClassName()
d) getElementsByTagName()
Answer: a) getElementById()
Which object is the global object in the browser environment?
a) Window
b) Document
c) Navigator
d) Form
Answer: a) Window
Which event occurs when a mouse button is clicked on an element?
a) click
b) mouseover
c) keydown
d) submit
Answer: a) click
Which method is used to read all cookies in JavaScript?
a) document.cookies
b) document.cookie
c) getCookie()
d) cookie.get()
Answer: b) document.cookie
What does the 'expires' attribute in a cookie specify?
a) When the cookie will expire

55
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

b) Where the cookie is stored


c) The domain of the cookie
d) The key of the cookie
Answer: a) When the cookie will expire
Which method removes a cookie in JavaScript?
a) deleteCookie()
b) removeCookie()
c) document.cookie = "name=; expires=..."
d) document.cookie = "name=; delete=true"
Answer: c) document.cookie = "name=; expires=..."
Which method is used to add event listeners in JavaScript?
a) addEvent()
b) addListener()
c) addEventListener()
d) listenEvent()
Answer: c) addEventListener()
Which property of the Window object returns the inner width of the browser?
a) window.height
b) window.innerWidth
c) window.outerWidth
d) window.width
Answer: b) window.innerWidth
Which event occurs when the user presses a key?
a) keydown
b) keyup
c) keypress
d) keyevent
Answer: a) keydown
Which property of the Navigator object returns the user's language?
a) navigator.language
b) navigator.lang
c) navigator.locale
d) navigator.region
Answer: a) navigator.language

56
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Which object represents the user's browser and environment in JavaScript?


a) Window
b) Document
c) Browser
d) Navigator
Answer: d) Navigator
Which method in JavaScript is used to stop a form from submitting?
a) event.preventDefault()
b) event.stopPropagation()
c) form.stopSubmit()
d) form.preventSubmit()
Answer: a) event.preventDefault()
What does the 'value' property represent in form elements?
a) The form's ID
b) The content inside the form
c) The data entered by the user
d) The name of the form
Answer: c) The data entered by the user
Which event is triggered when the user moves the mouse over an element?
a) mouseout
b) mousemove
c) mouseover
d) click
Answer: c) mouseover

Five-Mark Questions:
1. Explain the Document Object Model (DOM) and its structure.
2. What is the purpose of the getElementById() method in JavaScript?
3. What is an event listener, and how is it used in JavaScript?
4. Describe the process of creating a cookie in JavaScript.
5. How can you delete a cookie in JavaScript?

57
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Ten-Mark Questions:
1. Explain the methods and properties of the Window object in JavaScript.
2. What are cookies in JavaScript, and how are they used for session management?
3. Discuss the differences between getElementById() and querySelector() methods.
4. Explain how event handling works in JavaScript, with examples of mouse and
keyboard events.
5. Describe the process of creating, reading, and deleting cookies in JavaScript.

58
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

UNIT – 4
ASP. NET: Language Structure – page structure – page event, properties - compiler
directives.
HTML server controls – Anchor, Tables, Forms - Basic Web server controls–label, textbox,
button, image, links, check & Radio button, hyperlink.
ASP. NET:
Introduction to ASP.NET
ASP.NET is a web development framework created by Microsoft. It is used to build
dynamic web applications, websites, and services. It runs on the .NET Framework or
.NET Core and uses languages like C#, VB.NET, or F#.

What is ASP.NET?
1. ASP.NET stands for Active Server Pages .NET.
2. It allows developers to create websites that are:
o Dynamic: Content changes based on user actions.
o Data-driven: Connects to databases.
o Interactive: Supports user input and processing.

Why Use ASP.NET?


1. Easy to Learn: Simple structure with tools to help beginners.
2. Fast and Scalable: Efficient for small websites or large enterprise applications.
3. Secure: Built-in security features like authentication and authorization.
4. Cross-Platform: With ASP.NET Core, you can build apps that run on Windows,
macOS, and Linux.

How Does ASP.NET Work?


1. Server-Side Framework: ASP.NET runs on the server (not the browser).
o You write code on the server.
o The server sends HTML to the user's browser.
2. User Interaction:
o User clicks a button or submits a form.
o The server processes the request and updates the page.

59
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Basic Features of ASP.NET


1. Web Forms: Build web pages using drag-and-drop controls.
2. MVC (Model-View-Controller): Separates the logic, design, and data handling for
better management.
3. Server Controls: Built-in controls like buttons, textboxes, and grids.
4. Data Binding: Connect and display data from a database.
5. State Management: Remembers data during user sessions.

Language Structure, Page Structure, and Page Events

1. Language Structure in ASP.NET


ASP.NET follows a structured programming model combining:
Markup (Frontend): Written in HTML and ASP.NET server controls.
Code-Behind (Backend): Written in C# or VB.NET.
Components of ASP.NET’s language structure:
• Directives: Define page properties.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default" %>
• Server Controls: Interactive elements for user input.
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click"
/>
• Event Handlers: Backend methods to handle events.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Hello, ASP.NET!";
}

2. Page Structure in ASP.NET


ASP.NET pages are divided into two main parts:
(a) Markup (Default.aspx)
Defines the user interface using HTML and ASP.NET controls. Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="Default" %>
<!DOCTYPE html>

60
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

<html>
<head>
<title>ASP.NET Page Structure</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Welcome!"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Click"
/>
</form>
</body>
</html>
(b) Code-Behind (Default.aspx.cs)
Contains server-side logic in C# or VB.NET. Example:
using System;

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


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label1.Text = "Page Loaded";
}
}

protected void Button1_Click(object sender, EventArgs e)


{
Label1.Text = "Button Clicked!";
}
}

61
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

3. Page Events in ASP.NET


Page events occur during the lifecycle of an ASP.NET page. The most common events
include:
(a) Page Life Cycle Events
1. Page_PreInit:
o Raised before the page initializes.
o Example: Setting themes or master pages.
protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "DarkTheme";
}
2. Page_Init:
o Initializes controls.
o Example: Dynamic control creation.
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("Page Init Event");
}
3. Page_Load:
o Occurs when the page is loaded.
o Example: Setting initial values.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label1.Text = "Welcome to ASP.NET!";
}
}
4. Page_PreRender:
o Occurs just before rendering the page.
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("PreRender Event");
}

62
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

5. Page_Unload:
o Called when the page is unloaded from memory.
protected void Page_Unload(object sender, EventArgs e)
{
// Cleanup code
}

(b) Control Events


Triggered by user actions like button clicks.
• Example: Button click event.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Button was clicked!";
}

Summary
• Language Structure: Combines markup and backend logic.
• Page Structure: Divided into markup (UI) and code-behind (logic).
• Page Events: Manage page lifecycle and user interactions efficiently.
This structure simplifies the development of dynamic web applications in ASP.NET.

Properties and Compiler Directives in ASP.NET

1. Properties in ASP.NET
Properties are members of a class that act as a bridge between private fields and the
external world. They allow controlled access to the fields of a class in ASP.NET code-
behind.
Syntax of Properties
private string _name; // Private field

public string Name


{
get { return _name; } // Getter
set { _name = value; } // Setter

63
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Key Points
• Encapsulation: Protects private fields while providing controlled access.
• Read-Only/Write-Only Properties: By defining only get or set.
• Auto-Implemented Properties: A shorthand for simple properties.
• public string Name { get; set; }

Example
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
}

2. Compiler Directives in ASP.NET


Compiler directives are instructions for the compiler to alter the way code is
compiled. They do not affect the runtime behavior of the application.
Common Compiler Directives
1. #define and #undef
Define or undefine a symbol.
#define DEBUG
2. #if, #else, #elif, #endif
o Conditional compilation based on symbols.
#if DEBUG
Console.WriteLine("Debug mode is active");
#else
Console.WriteLine("Release mode is active");
#endif
3. #region and #endregion
o Helps organize code into collapsible regions.
#region MyCode
Console.WriteLine("Hello, World!");
#endregion

64
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

4. #warning and #error


o Generate custom warnings or errors during compilation.
#warning This is a warning message
#error This is an error message
5. #pragma
o Controls compiler warnings.
#pragma warning disable CS0168 // Disables a specific warning
int unusedVariable;
#pragma warning restore CS0168 // Restores the warning

Examples in ASP.NET
Compiler Directives in Action
#define DEBUG

using System;

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


{
protected void Page_Load(object sender, EventArgs e)
{
#if DEBUG
Response.Write("Debug mode active.");
#else
Response.Write("Release mode active.");
#endif
}
}
Using Properties in ASP.NET Code
public partial class Default : System.Web.UI.Page
{
public string UserName { get; set; }

protected void Page_Load(object sender, EventArgs e)


{

65
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

UserName = "John Doe";


Response.Write("Hello, " + UserName);
}
}
Summary
1. Properties: Control access to class fields using get and set methods.
2. Compiler Directives: Provide instructions for the compiler to modify code behavior
during compilation (e.g., debugging, warnings).
Both are essential for writing structured, maintainable, and optimized ASP.NET applications.

HTML Server Controls in ASP.NET


HTML server controls in ASP.NET are standard HTML elements enhanced to
support server-side processing. These controls are declared in an ASP.NET page and can be
accessed and manipulated using server-side code.

1. Anchor Server Control


The anchor (<a>) control creates hyperlinks in web pages. As a server control, it supports
server-side events.
Syntax
<a id="anchorLink" runat="server" href="https://example.com">Click Here</a>
Key Features
• The runat="server" attribute enables server-side processing.
• The href attribute specifies the destination URL.
Example
<a id="homeLink" runat="server" href="Home.aspx">Go to Home</a>
Manipulating in Code-Behind
homeLink.HRef = "https://www.example.com";
homeLink.InnerHtml = "Visit Example";

2. Table Server Control


The table (<table>) control is used to display data in a structured, tabular format.
Syntax
<table id="serverTable" runat="server">
<tr>

66
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
Key Features
• Dynamically add rows or cells via server-side code.
• Enhanced control over the table layout.
Example
// Adding a new row to the table in code-behind
TableRow row = new TableRow();
TableCell cell1 = new TableCell { Text = "New Data 1" };
TableCell cell2 = new TableCell { Text = "New Data 2" };

row.Cells.Add(cell1);
row.Cells.Add(cell2);
serverTable.Rows.Add(row);

3. Form Server Control


The form (<form>) control is the foundation of user input and data submission in
web pages.
Syntax
<form id="form1" runat="server">
<input type="text" id="username" runat="server" />
<input type="submit" value="Submit" />
</form>
Key Features
• Captures and submits data to the server.
• Supports server-side validation and processing.
Example
Frontend Code

67
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

<form id="form1" runat="server">


<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" Text="Submit" runat="server"
OnClick="btnSubmit_Click" />
</form>
Code-Behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = txtName.Text;
Response.Write("Hello, " + name);
}

NOTE:
1. Anchor Control: Creates hyperlinks, dynamically change href using server code.
2. Table Control: Displays data in rows and columns; rows can be added or modified
dynamically.
3. Form Control: Accepts user input and allows interaction between client and server.
These server controls make HTML elements more interactive and easier to manage within
ASP.NET applications.

Basic Web Server Controls in ASP.NET


ASP.NET provides various Web Server Controls that extend standard HTML
controls to support server-side processing. These controls are part of the
System.Web.UI.WebControls namespace.

1. Label
The Label control is used to display static or dynamic text on a web page.
Syntax
<asp:Label ID="lblMessage" runat="server" Text="Hello, ASP.NET!"></asp:Label>
Key Features
• Displays dynamic messages using Text property.
• Can be updated in code-behind.
Example
lblMessage.Text = "Welcome to ASP.NET!";

68
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

2. TextBox
The TextBox control is used for user input in text format.
Syntax
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
Key Features
• Supports single-line, multi-line, or password input (TextMode property).
• Use Text property to get or set user input.
Example
string name = txtName.Text;

3. Button
The Button control triggers an event when clicked.
Syntax
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
Key Features
• The OnClick event executes server-side code.
Example (Code-Behind)
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblMessage.Text = "Button clicked!";
}

4. Image
The Image control displays an image on the page.
Syntax
<asp:Image ID="imgLogo" runat="server" ImageUrl="logo.png" />
Key Features
• Dynamically change the image source using the ImageUrl property.
Example
imgLogo.ImageUrl = "newlogo.png";

5. LinkButton
The LinkButton control acts like a hyperlink but supports server-side events.
Syntax

69
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

<asp:LinkButton ID="lnkDetails" runat="server" OnClick="lnkDetails_Click">View


Details</asp:LinkButton>
Example (Code-Behind)
protected void lnkDetails_Click(object sender, EventArgs e)
{
Response.Redirect("Details.aspx");
}

6. CheckBox
The CheckBox control is used to select/unselect options.
Syntax
<asp:CheckBox ID="chkAgree" runat="server" Text="I agree to the terms" />
Key Features
• Check status can be read using the Checked property.
Example
if (chkAgree.Checked)
{
lblMessage.Text = "Thank you for agreeing!";
}

7. RadioButton
The RadioButton control is used for single-choice options within a group.
Syntax
<asp:RadioButton ID="rdoMale" runat="server" GroupName="Gender" Text="Male" />
<asp:RadioButton ID="rdoFemale" runat="server" GroupName="Gender" Text="Female" />
Key Features
• Group radio buttons using the GroupName property.
• Use the Checked property to determine the selected option.
Example
if (rdoMale.Checked)
{
lblMessage.Text = "You selected Male.";
}

70
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

8. HyperLink
The HyperLink control creates navigational links.
Syntax
<asp:HyperLink ID="lnkHome" runat="server" NavigateUrl="Home.aspx" Text="Go to
Home" />
Key Features
• Use the NavigateUrl property to specify the destination.
Example
lnkHome.NavigateUrl = "https://www.example.com";

Control Description Key Property

Label Displays text Text

TextBox Accepts user input Text, TextMode

Button Triggers events on click OnClick

Image Displays an image ImageUrl

LinkButton Acts as a hyperlink with events OnClick

CheckBox Select/unselect option Checked

RadioButton Single-choice option within group GroupName, Checked

HyperLink Creates navigational links NavigateUrl

These controls enhance user interactivity and simplify server-side handling of web forms in
ASP.NET.

UNIT – 4
CHOOSE THE BEST ANSWER:
1. What does ASP.NET stand for?
a) Active Service Pages .NET
b) Application Server Pages .NET
c) Active Server Pages .NET
d) Advanced Server Programming .NET
Answer: c) Active Server Pages .NET
2. Which property in the <%@ Page %> directive sets the programming language?
a) AutoEventWireup

71
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

b) Language
c) Inherits
d) CodeFile
Answer: b) Language
3. What is the main purpose of the runat="server" attribute?
a) To define the control as a client-side element
b) To make the control visible
c) To enable server-side processing
d) To handle JavaScript events
Answer: c) To enable server-side processing
4. Which ASP.NET page lifecycle event is raised before the page initializes?
a) Page_Init
b) Page_Load
c) Page_PreInit
d) Page_Unload
Answer: c) Page_PreInit
5. Which directive is used to conditionally compile code in ASP.NET?
a) #pragma
b) #region
c) #if
d) #define
Answer: c) #if
6. What is the default property to read user input in a TextBox control?
a) Input
b) Value
c) Text
d) Content
Answer: c) Text
7. Which control in ASP.NET is used to display static or dynamic text?
a) TextBox
b) Label
c) Button
d) HyperLink
Answer: b) Label

72
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

8. Which ASP.NET server control is used to group multiple radio buttons?


a) GroupBox
b) Panel
c) RadioButton
d) GroupName
Answer: c) RadioButton
9. Which server control is used for creating navigational links in ASP.NET?
a) HyperLink
b) LinkButton
c) Anchor
d) Button
Answer: a) HyperLink
10. Which compiler directive helps organize code into collapsible sections?
a) #define
b) #pragma
c) #region
d) #error
Answer: c) #region
11. What ASP.NET feature allows developers to dynamically connect controls to
data?
a) State Management
b) Data Binding
c) Server Controls
d) Code-Behind
Answer: b) Data Binding
12. What is the main function of the ImageUrl property in the Image control?
a) Sets the size of the image
b) Specifies the source of the image
c) Adds a tooltip to the image
d) Sets the alternate text for the image
Answer: b) Specifies the source of the image
13. Which of these is a built-in server control for single-choice options?
a) CheckBox
b) TextBox

73
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

c) RadioButton
d) Label
Answer: c) RadioButton
14. Which property is used to redirect users using a HyperLink control?
a) Text
b) NavigateUrl
c) HRef
d) Destination
Answer: b) NavigateUrl
15. What is the purpose of the AutoEventWireup property in an ASP.NET page?
a) Automatically generates code
b) Wires events automatically to handlers
c) Enables client-side processing
d) Defines the control's ID
Answer: b) Wires events automatically to handlers
Five Mark Questions
1. What is the significance of the runat="server" attribute in ASP.NET HTML server
controls?
2. Explain the role of the Page_Load event in the ASP.NET page lifecycle.
3. Describe the difference between HTML controls and Web server controls in ASP.NET.
4. What is the use of the OnClick event in a Button control in ASP.NET? Provide an
example.
5. Explain the difference between the TextBox and Label controls in ASP.NET.
Ten Mark Questions
1. Explain the structure of an ASP.NET page, including the markup and code-behind
components. Provide an example.
2. Discuss the page lifecycle in ASP.NET, focusing on the key events such as Page_Init,
Page_Load, and Page_Unload.
3. Explain the use of compiler directives in ASP.NET with examples of #define, #region,
and #if.
4. Describe how HTML server controls like Anchor, Tables, and Forms are used in
ASP.NET. Provide examples for each.
5. Discuss the usage of Basic Web server controls in ASP.NET, such as Label, TextBox,
Button, and CheckBox. Explain their key properties and provide code examples.

74
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

UNIT – 5
Request and Response objects - Working with data – OLEDB connection class, Command
class Transaction class, data adaptor class, data set class.
Security: Authentication, IP Address, Secure by SSL & Client Certificates.

Request and Response Objects in ASP.NET


The Request and Response objects are used for handling HTTP requests and responses
in an ASP.NET web application. They provide a way to access client data (request) and send
data back to the client (response).
Request Object
The Request object provides information about the HTTP request sent by the client to
the server. It is used to gather data submitted by the client, such as form input, query strings,
cookies, headers, etc.
Features of the Request Object:
1. Access to HTTP Methods:
o Request.QueryString: Access data passed via the URL (GET method).
o Request.Form: Access data submitted via an HTML form (POST method).
o Request.Cookies: Access cookies sent by the client.
2. Methods and Properties:
o Request.Url: Returns the full URL of the request.
o Request.HttpMethod: Returns the HTTP method (GET, POST, etc.).
o Request.Headers: Access HTTP request headers.
o Request.Cookies: Returns cookies sent from the client.
Example:
string userName = Request.Form["txtUserName"];
string pageUrl = Request.Url.ToString();

Response Object
The Response object is used to send information from the server to the client. It can
return content (HTML, JSON, etc.), set HTTP headers, and control redirection.
Features of the Response Object:
1. Sending Data to the Client:
o Response.Write(): Outputs content directly to the browser.
o Response.Redirect(): Redirects the user to another page.

75
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

o Response.End(): Ends the response and stops further processing.


2. Methods and Properties:
o Response.StatusCode: Sets the status code of the response (e.g., 200 for
success).
o Response.Cookies: Sends cookies to the client.
o Response.Headers: Adds custom headers to the response.
Example:
Response.Write("Hello, ASP.NET!");
Response.Redirect("Home.aspx");

NOTE:
• Request Object: Allows you to access and manipulate incoming request data from the
client.
• Response Object: Allows you to send data back to the client and control page
redirection.

Working with data


In ASP.NET, working with data involves connecting to a database, retrieving data, and
displaying it on web pages. Here's a simple overview of how you can work with data in
ASP.NET:
1. Connecting to a Database
SQL Connection: Use SqlConnection to connect to a SQL database.
Example:
using System.Data.SqlClient;

string connectionString = "your_connection_string";


SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
2. Retrieving Data
You can use SqlCommand to execute SQL queries or stored procedures to retrieve
data.
Example:
string query = "SELECT * FROM Users";
SqlCommand command = new SqlCommand(query, connection);

76
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

SqlDataReader reader = command.ExecuteReader();


while (reader.Read())
{
string userName = reader["Username"].ToString();
Console.WriteLine(userName);
}
3. Displaying Data on a Web Page
Web Controls: Use server controls like GridView, Repeater, or DataList to display
data.
Example using GridView:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True"></asp:GridView>
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Users",
connection);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
4. Inserting Data into the Database
You can use SqlCommand to insert data.
Example:
string insertQuery = "INSERT INTO Users (Username, Password) VALUES
(@Username, @Password)";
SqlCommand command = new SqlCommand(insertQuery, connection);
command.Parameters.AddWithValue("@Username", "NewUser");
command.Parameters.AddWithValue("@Password", "password123");
command.ExecuteNonQuery();
5. Updating Data
You can also update existing records using SQL UPDATE statements.
Example:
string updateQuery = "UPDATE Users SET Password = @Password WHERE
Username = @Username";
SqlCommand command = new SqlCommand(updateQuery, connection);
command.Parameters.AddWithValue("@Username", "ExistingUser");

77
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

command.Parameters.AddWithValue("@Password", "newPassword");
command.ExecuteNonQuery();
6. Deleting Data
Deleting data is done using DELETE statements.
Example:
string deleteQuery = "DELETE FROM Users WHERE Username = @Username";
SqlCommand command = new SqlCommand(deleteQuery, connection);
command.Parameters.AddWithValue("@Username", "UserToDelete");
command.ExecuteNonQuery();
NOTE:
• SqlConnection: Connects to the database.
• SqlCommand: Executes SQL queries.
• SqlDataReader: Reads the data from the database.
• GridView: Displays data in a tabular format on a web page.

In ASP.NET, when working with databases, the OLEDB classes can be used to connect and
interact with data sources like Microsoft Access, Excel, or other OLEDB-compatible
databases. Here’s a simple explanation of the key classes:
1. OLEDB Connection Class (OLEDBConnection)
Purpose: This class is used to establish a connection to a data source (like Access or
Excel) using OLEDB providers.
Example:
using System.Data.OLEDB;

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data


Source=your_database.accdb;";
OLEDBConnection connection = new OLEDBConnection(connectionString);
connection.Open();
2. OLEDB Command Class (OLEDBCommand)
Purpose: Used to execute SQL commands (like SELECT, INSERT, UPDATE, or
DELETE) on the connected data source.
Example:
string query = "SELECT * FROM Users";
OLEDBCommand command = new OLEDBCommand(query, connection);

78
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

OLEDBDataReader reader = command.ExecuteReader();


while (reader.Read())
{
Console.WriteLine(reader["Username"]);
}
3. Transaction Class (OLEDBTransaction)
Purpose: This class is used to manage database transactions. A transaction ensures that a
set of operations (like multiple INSERT, UPDATE, or DELETE statements) are executed
together as a single unit.
Example:
OLEDBTransaction transaction = connection.BeginTransaction();
OLEDBCommand command = connection.CreateCommand();
command.Transaction = transaction;

try
{
command.CommandText = "UPDATE Users SET Password = 'newPassword' WHERE
Username = 'user1'";
command.ExecuteNonQuery();
transaction.Commit(); // Commit transaction if no error
}
catch
{
transaction.Rollback(); // Rollback if error occurs
}
4. Data Adapter Class (OLEDBDataAdapter)
Purpose: This class serves as a bridge between the OLEDBConnection and a DataSet. It
is used to fill the dataset with data and update the database.
Example:
OLEDBDataAdapter dataAdapter = new OLEDBDataAdapter("SELECT * FROM
Users", connection);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Users");

79
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

5. DataSet Class (DataSet)


Purpose: A DataSet is an in-memory representation of data. It can hold multiple tables
and relationships between them. It allows you to work with data in a disconnected
manner.
Example:
OLEDBDataAdapter dataAdapter = new OLEDBDataAdapter("SELECT * FROM
Users", connection);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "Users");

// Access the data in the DataSet


foreach (DataRow row in dataSet.Tables["Users"].Rows)
{
Console.WriteLine(row["Username"]);
}

NOTE:
OLEDBConnection: Establishes a connection to a database.
OLEDBCommand: Executes SQL queries or commands.
OLEDBTransaction: Manages transactions to group multiple operations.
OLEDBDataAdapter: Fills a DataSet with data from the database and updates the
database.
DataSet: Holds data in-memory, supporting multiple tables and relationships.
These classes are part of the System.Data.OLEDB namespace and help in managing and
manipulating data from various data sources using OLEDB technology.

Security: Authentication, IP Address, Secure by SSL & Client Certificates.


In ASP.NET, security is crucial for ensuring that your web application is safe from
unauthorized access and data breaches. Here’s a simple breakdown of security measures
related to authentication, IP addresses, SSL (Secure Sockets Layer), and client certificates:
1. Authentication
Purpose: Authentication verifies the identity of users who try to access the application.
Types:
Forms Authentication: A common method where users are required to log in

80
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

with a username and password.


Windows Authentication: Uses the credentials of the user logged into the
Windows operating system.
Example (Forms Authentication):
// In the Web.config file, enable forms authentication
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="30"/>
</authentication>
</system.web>
// In the code-behind, authenticate the user
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.RedirectFromLoginPage(username, false);
}
else
{
// Invalid credentials
}

2. IP Address
Purpose: Restricting access based on the user's IP address helps prevent unauthorized
users from accessing the application.
How to Implement: You can set rules to allow or deny access from specific IP addresses
in the web.config file or programmatically.
Example (Allow access from a specific IP):
<system.webServer>
<security>
<ipSecurity allowUnlisted="false">
<add ipAddress="192.168.1.100" allowed="true"/>
<add ipAddress="0.0.0.0" allowed="false"/>
</ipSecurity>
</security>
</system.webServer>

81
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

Programmatic approach to check IP:


string userIP = Request.UserHostAddress;
if (userIP != "192.168.1.100")
{
Response.Redirect("AccessDenied.aspx");
}

3. Secure by SSL (Secure Sockets Layer)


Purpose: SSL is used to encrypt data sent between the client and server, ensuring that
sensitive information like passwords and personal data is protected.
How to Implement:
Enable SSL in IIS: Ensure SSL is enabled on your server and bind HTTPS to
your website.
Redirect HTTP to HTTPS: Force secure communication by redirecting users
from HTTP to HTTPS.
Example (Web.config Redirect):
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Redirect to HTTPS" enabled="true"
stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

82
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

4. Client Certificates
Purpose: Client certificates are used for mutual authentication where both the client and
server authenticate each other.
How to Implement:
Require Client Certificates in IIS: Set up IIS to require a valid client certificate
for access.
Access Client Certificate in ASP.NET:
X509Certificate2 cert = Request.ClientCertificate;
if (cert != null)
{
// Use certificate details for further processing
string certSubject = cert.Subject;
string certIssuer = cert.Issuer;
}

NOTE:
1. Authentication: Verifies the identity of users through methods like forms
authentication or Windows authentication.
2. IP Address: Restricts access based on the user's IP address for additional security.
3. Secure by SSL: Uses encryption (SSL) to protect data in transit between the client
and server.
4. Client Certificates: Provides mutual authentication, where both the client and the
server authenticate each other using certificates.

UNIT – 5
CHOOSE THE BEST ANSWER:
1. What is the purpose of authentication in web security?
a) To verify the user's identity
b) To encrypt data
c) To limit access based on IP
d) To restrict website traffic
Answer: a) To verify the user's identity

83
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

2. Which of the following is a type of authentication in ASP.NET?


a) IP Authentication
b) Forms Authentication
c) SSL Authentication
d) Encryption Authentication
Answer: b) Forms Authentication

3. In which file is Forms Authentication enabled in an ASP.NET application?


a) Global.asax
b) Web.config
c) Site.master
d) App.config
Answer: b) Web.config

4. What does Windows Authentication use for verifying users?


a) Username and password stored in the database
b) Username and password from a file
c) User credentials from the Windows operating system
d) API keys
Answer: c) User credentials from the Windows operating system

5. What action does the FormsAuthentication.RedirectFromLoginPage method


perform?
a) Redirects the user to the registration page
b) Redirects the user to the home page after a successful login
c) Validates the user's credentials
d) Logs the user out of the system
Answer: b) Redirects the user to the home page after a successful login

6. What does the ipSecurity element in the web.config file do?


a) Encrypts data between client and server
b) Limits access to certain IP addresses
c) Configures authentication settings
d) Defines SSL settings
Answer: b) Limits access to certain IP addresses
7. In which section of the web.config file do you configure IP address restrictions?

84
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

a) <authentication>
b) <security>
c) <ipSecurity>
d) <serverSettings>
Answer: b) <security>

8. What does the Request.UserHostAddress method in ASP.NET return?


a) The IP address of the user
b) The user’s device name
c) The session ID
d) The user’s location
Answer: a) The IP address of the user

9. How can you force users to access your website over a secure connection (HTTPS)?
a) Enable cookies in the browser
b) Use SSL encryption
c) Redirect HTTP to HTTPS in web.config
d) Change the server port
Answer: c) Redirect HTTP to HTTPS in web.config

10. What is the role of SSL in web security?


a) It encrypts data between the client and server
b) It verifies the identity of the user
c) It restricts access to certain IP addresses
d) It logs all user activity on the website
Answer: a) It encrypts data between the client and server

11. What does the <rewrite> section in web.config do?


a) Redirects URLs from HTTP to HTTPS
b) Configures the server settings
c) Defines server-side scripts
d) Provides backup options for website data
Answer: a) Redirects URLs from HTTP to HTTPS

85
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

12. What is the purpose of client certificates in web security?


a) To encrypt the data sent between client and server
b) To authenticate the user via username and password
c) To enable mutual authentication between the client and server
d) To track user activity
Answer: c) To enable mutual authentication between the client and server

13. How do you access a client certificate in ASP.NET?


a) Request.UserCertificate
b) Request.ClientCertificate
c) Response.Certificate
d) HttpClient.Certificate
Answer: b) Request.ClientCertificate

14. Which of the following is required to use client certificates for authentication?
a) SSL must be disabled
b) A valid client certificate must be installed in IIS
c) Cookies must be enabled
d) Usernames and passwords must be disabled
Answer: b) A valid client certificate must be installed in IIS

15. What is the main purpose of X509Certificate2 class in ASP.NET?


a) To manage database connections
b) To encrypt sensitive data
c) To handle client certificates
d) To log user activity
Answer: c) To handle client certificates

Five-Mark Questions:
1. Explain the purpose of authentication in web security and list two types of
authentication used in ASP.NET.
2. What is IP address filtering, and how can it be implemented in ASP.NET to restrict
unauthorized access?
3. Describe the role of SSL (Secure Sockets Layer) in securing data between client and
server.

86
AVS College of Arts & Science (Autonomous)
II – BBA WEB TECHNOLOGY THEORY AND PRACTICE

4. How does ASP.NET implement Forms Authentication? Provide an example of how to


enable and use Forms Authentication in the web.config file.
5. What is the significance of client certificates in web security, and how can they be
used for mutual authentication in ASP.NET?

Ten-Mark Questions:
1. Discuss the different authentication methods in ASP.NET, highlighting the
differences between Forms Authentication and Windows Authentication. Provide
examples of each.
2. Explain how IP address filtering works in ASP.NET to enhance security. Provide an
example of how to configure IP address restrictions in the web.config file and
programmatically check the user's IP address.
3. Describe how SSL (Secure Sockets Layer) improves security in web applications.
Discuss how to configure SSL in an ASP.NET application and redirect traffic from
HTTP to HTTPS using the web.config file.
4. Explain the concept of mutual authentication using client certificates in ASP.NET.
How can you implement this feature in IIS and access the client certificate in the
application code?
5. Illustrate the use of authentication, IP address filtering, SSL, and client certificates in
securing an ASP.NET web application. Explain how each method contributes to the
overall security of the application.

87
AVS College of Arts & Science (Autonomous)

You might also like