ASP.NET Web Forms

ASP.NET Web Forms

ASP.NET Web Form Tutorial

ASP.NET is an open-source application framework created by Microsoft for building modern web apps and services. It allows you to create dynamic web pages using .NET with C#, VB.NET, or F#. ASP.NET extends the .NET platform with tools and libraries specifically designed for building web apps.

.NET is platform-independent, meaning applications developed with .NET can run on multiple platforms. To run .NET applications on a machine, it must first have the .NET Runtime installed. Microsoft has provided us with three different .NET Runtimes over time:

  1. .NET Framework Runtime: Launched in 2002, this runtime is available only for Windows platforms. The first version was 1.0, and the latest version is 4.8.

  2. .NET Core Runtime: Launched in 2016, this runtime is available for multiple platforms like Windows, Linux, and Mac. The first version was 1.0, and the latest version is 3.1.

  3. .NET Runtime: Launched in 2020, this runtime is also available for multiple platforms like Windows, Linux, and Mac. It combines .NET Framework and .NET Core into "One .NET." The first version started with 5.0, known as .NET 5, and the latest version is .NET 6.

In the .NET Framework, we have the ASP.NET Framework for building web applications. Under this, we have different options like:

In .NET Core, .NET 5, and .NET 6, we have the ASP.NET Core Framework for building web applications. Here, we also have different options like:

Note: ASP.NET Core is the open-source version of ASP.NET that works on Windows, Linux, macOS, and Docker. It was first released in 2016 and is a redesign of the older Windows-only versions of ASP.NET. Performance is a key focus of ASP.NET Core, and it is faster than many other web frameworks according to TechEmpower benchmarks. Like the rest of .NET, ASP.NET is open source on GitHub, with over 100,000 contributions and 3,700 companies contributing.

Developing Web Applications:

Long ago, Microsoft introduced ASP (Active Server Pages), which required VBScript or VBScript support to build ASP applications.

Today, ASP.NET, developed by Microsoft, is the next version of ASP. ASP.NET supports any .NET language, with C# being the most popular, as well as VB.NET and others.

Other technologies include PHP, which uses PHP scripts, and JSP & Servlets, which use Java.

In this course, we will learn how to develop ASP.NET applications using C#. To do this, we need to use several technologies, including HTML, CSS, JavaScript/jQuery, C#, and a web server. After creating the application, we need to install a web server so it can be accessed from anywhere and on any device. This server will host our application.

There are many web servers available, such as IIS (Internet Information Services), Apache Server, and GWS Server. For our course, we will use IIS to host our application.

IIS Web Server: In the IIS web server, we install a web application, which contains web pages. These web pages can be accessed from various locations.

Applications:

Applications can be divided into three main categories:

  1. Desktop Applications: Installed directly on a computer. Examples: MS Office, Skype Messenger, Zoom, Browsers, etc.

  2. Mobile Applications: Installed on a mobile device. Examples: WhatsApp, Swiggy, Zomato, Uber, Ola, etc.

  3. Web Applications: Hosted on a central server and accessed from various devices and locations via the internet. Examples: Facebook, Gmail, Amazon, Flipkart, etc.

Web applications are different from desktop and mobile applications because they are not installed on a user's device. Instead, they are accessed through a web browser, which is available on all devices, making them accessible from anywhere with an internet connection.

Desktop Applications vs Web Applications:

  • ⮚ Web applications need to be installed only once on a single computer, while desktop apps must be installed separately on each computer.

  • ⮚ Updating a web app needs to be done only on the single computer where it is installed, whereas desktop apps need to be updated on every computer.

  • ⮚ Desktop apps are confined to a particular location and have usability constraints, while web apps are convenient for users to access from any location using the internet.

  • ⮚ Web applications rely heavily on internet connectivity and speed, so poor connectivity can cause performance issues, whereas desktop apps are standalone and do not face such issues.

  • ⮚ Web applications are completely internet-dependent and consume more bandwidth, whereas desktop apps are partially internet-dependent and consume less bandwidth.

  • ⮚ To build desktop applications with .NET languages, we use technologies like Console Apps, Windows Apps, and WPF (Windows Presentation Foundation) Apps. Similarly, to build web applications, we use technologies like ASP.NET and ASP.NET Core.

Web Applications vs Mobile Applications:

  • ⮚ Web apps need an internet connection to work, while mobile apps can work offline.

  • ⮚ Mobile apps are faster and more efficient but need regular updates from the user. Web apps update themselves.

  • ⮚ Mobile apps are made for systems like iOS and Android and can be used anywhere by downloading them. Web apps can run on any operating system, including desktops and mobiles.

  • ⮚ Mobile apps are generally safer than web apps.

  • ⮚ Web apps are usually cheaper to develop than mobile apps.

Desktop Applications vs Mobile Applications:

  • ⮚ Desktop apps run on stationary computers or laptops, while mobile apps run on phones or tablets.

  • ⮚ Mobile apps have limits on storage and connectivity.

  • ⮚ Mobile apps use the phone’s features like the microphone, camera, and location services.

  • ⮚ Desktop apps are usually more flexible and powerful than mobile apps.

  • ⮚ Mobile users interact with their devices differently than with traditional apps. For example, mobile apps are designed for vertical use, while desktop apps can be designed for horizontal use.

Internet

The Internet is a global system of Interconnected computer networks that use standard protocols (TCP/IP) to link billions of devices worldwide. It is made up of many private, public, academic, business, and government networks, ranging from local to global. These networks are connected by various electronic, wireless, and optical technologies. The Internet carries a wide range of information, resources, and services, including the World Wide Web (WWW), email, and peer-to-peer networks for file sharing and calls.

World Wide Web (WWW)

  • The Web is a large network of computers worldwide.

  • All the computers on the Web can talk to each other.

  • These computers use a communication protocol called HTTP (or HTTPS for secure communication).

How the WWW Works

  • Web information is stored in files called Web Pages.

  • A collection of Web Pages is known as a Website or Web Application.

  • Websites or Web Applications are hosted on computers called Web Servers.

  • Devices that access and read the Web Pages are called Web Clients.

  • Web Clients view the Web Pages using a program called a Web Browser.

How the Web Browser fetch a Web Page

  • A web browser fetches a web page from a web server by sending a request called an "HTTP Request." This request includes the page address, known as a URL (Uniform Resource Locator).

  • An example of a URL might look like this: http(s)://www.google.com:80/default.html.

  • Format of a URL: <Protocol>://<Domain Name>:<Port>/<Request Page>.

How the Browser Display a Web Page

  • All web pages contain instructions on how they should be displayed. The web browser reads these instructions and renders the page accordingly.

  • The most common display instructions are called HTML, CSS, JavaScript, and Metadata.

What is a Web Server

  • A collection of web pages is called a Website or Web Application.

  • To allow others to view your web pages, you must publish your website or web application.

  • Publishing involves copying your site or application to a web server.

  • While your own PC can act as a web server if it’s connected to a network, it’s more common to use a hosting service provided by an Internet Service Provider (ISP).

What is an Internet Service Provider (ISP)

  • An ISP provides Internet services, one of which is web hosting.

  • Web hosting means storing your website or web application on a public server.

  • Web hosting often includes additional services like email hosting and domain name registration.

Summary

  • To make your website or application accessible to others, you need to copy it to a public server.

  • While you can use your own PC as a web server, it’s more common to let an ISP host your site.

  • Web hosting services typically include domain name registration and email services.

  • Hosting your site on your own server is an option, but consider the following points:

    1. Hardware Costs: To run a professional website or application, you’ll need powerful server hardware. A basic PC won’t suffice, and you’ll also need a permanent, high-speed internet connection.

    2. Software Costs: Server licenses are often more expensive than client licenses and may limit the number of users.

    3. Labor Costs: Running your own server involves installing hardware and software, dealing with bugs and viruses, and ensuring the server is constantly operational.

Benefits of Using an Internet Service Provider (Public Server)

Renting a web server from an Internet Service Provider (ISP) is a common option, especially for small businesses. Many companies host their websites or web applications on servers provided by ISPs. Here are some advantages:

  1. Connection Speed: Most ISPs offer very fast connections to the Internet.

  2. Security and Stability: ISPs specialize in web hosting. You can expect their servers to have over 99% uptime, the latest software updates, and strong virus protection.

  3. Powerful Hardware: ISPs often have powerful web servers that can be shared by several companies. They usually offer effective load balancing and necessary backup servers.

Things to Consider with an ISP

  1. 24-Hour Support: Ensure your ISP offers 24-hour support. Avoid situations where you can't fix critical problems immediately. Toll-free phone support is important if you don’t want to pay for long-distance calls.

  2. Daily Backup: Make sure your ISP runs daily backups to prevent data loss.

  3. Traffic Volume: Check the ISP’s traffic volume restrictions. Ensure you won’t incur high costs for unexpected traffic spikes if your site becomes popular.

  4. Content Restrictions: Review the ISP’s content restrictions if you plan to publish pictures, videos, or sound files. Make sure these are allowed.

  5. Email Capabilities: Confirm that your ISP supports the email features you need.

  6. Database Access: If your site uses databases, verify that the ISP supports the necessary database access.

What is TCP/IP

TCP/IP stands for Transmission Control Protocol/Internet Protocol. It is a set of protocols used for communication between computers over a network. It defines how electronic devices should be connected and how data should be transmitted between them.

  • TCP: Responsible for breaking down data into small packets for transmission over a network and reassembling them upon arrival.

  • IP: Manages communication between computers, including addressing, sending, and receiving data packets over the Internet.

TCP/IP Protocols for the Web

Web browsers and servers use TCP/IP protocols to connect to the Internet. Common TCP/IP protocols include:

  1. HTTP (HyperText Transfer Protocol): Manages communication between a web server and a web browser. It is used to send requests from a web client (browser) to a web server and return web content (web pages) from the server to the client.

  2. HTTPS (Secure HTTP): Ensures secure communication between a web server and a web browser. It is typically used for credit card transactions and other sensitive data.

  3. FTP (File Transfer Protocol): Handles the transfer of files between computers.

  4. SMTP (Simple Mail Transfer Protocol): Used to send and receive emails.

IP is Connectionless

  • Connectionless Protocol: IP does not keep a dedicated connection between two computers. This reduces the need for dedicated network lines, allowing many computers to communicate at the same time.

  • Packet Routing: IP breaks messages into small independent packets, which are routed through the Internet to the correct destination.

IP Routers:

  • Routing: When an IP packet is sent from a computer, it reaches an IP router. The router's job is to send the packet to the right destination, either directly or through another router.

  • Analogy: Using IP is like sending a long letter as many small postcards, each finding its own way to the receiver.

IP Addresses

  • Unique Identification: Every device on the network has its own unique IP address.

  • Structure: IP addresses are 32-bit numbers, usually written as four numbers separated by periods (e.g., 31.13.65.36).

  • Necessity: Each device needs a unique IP address to connect to the Internet, and each IP packet must have an address to reach another computer.

Domain Names:

  • Easier to Remember: Domain names are easier to remember than numeric IP addresses. For example, “facebook.com” is a domain name.

  • Translation: Domain names are translated into IP addresses by a Domain Name Server (DNS). DNS servers worldwide are responsible for this translation.

  • Registration: When a new domain name is registered, DNS servers worldwide are updated with the corresponding IP address.

What is a Domain Name

A domain name is a unique name for a website, such as "google.com" or "facebook.com." Registering a domain name is a key step in creating a website.

  • Registration: Domain names must be registered with a domain name registrar. The registrar adds the domain name to a global registry, along with the corresponding IP address, which is stored on DNS servers.

What is DNS

DNS stands for Domain Name System. A DNS server informs other computers on the Internet about a domain name and its associated IP address.

Registering a Domain

  • Process: Domains can be registered through domain name registration companies, which provide tools to search for available domain names and offer various domain name extensions.

  • Choosing a Domain Name: When selecting a domain name, consider its purpose: to provide an easy way for people to reach your website. The best domain names are short, meaningful, clear, and have good exposure.

What is Web Hosting

Web hosting is a service provided by companies (web hosts) that sell or lease space on a server where you can store the files that make your website accessible on the Internet. You typically need to own a domain, and web hosting companies can help you purchase one.

What is Shared Hosting

Shared hosting is a popular hosting option where multiple websites are hosted on a single physical server. Since most websites don’t use many server resources, shared hosting allows providers to offer stable service at a low cost. It allows you to share hosting space and costs with others while still getting the speed and space your small business website needs.

Domain Name Servers (DNS)

DNS is like the Internet's phone book. DNS servers keep a list of domain names and convert them into IP addresses. This is needed because domain names are easy for people to remember, but computers use IP addresses to access websites. All DNS server information is collected and stored at the Central Registry. Hosting companies and Internet Service Providers (ISPs) regularly update DNS information with the Central Registry.

The Internet Assigned Numbers Authority (IANA)

IANA manages global IP address allocations and delegates this responsibility to five Regional Internet Registries (RIRs). These RIRs allocate IP address blocks to local Internet registries like ISPs and other entities. The world is divided into five RIRs:

  1. AFRINIC: African Network Information Center, for Africa.

  2. ARIN: American Registry for Internet Numbers, for the United States, Canada, parts of the Caribbean, and Antarctica.

  3. APNIC: Asia-Pacific Network Information Centre, for Asia, Australia, New Zealand, and neighboring countries.

  4. LACNIC: Latin America and Caribbean Network Information Centre, for Latin America and parts of the Caribbean.

  5. RIPE NCC: Reseaux IP Europeens Network Coordination Centre, for Europe, Russia, the Middle East, and Central Asia.

Until now, you might have created some web pages using HTML, JavaScript, and CSS, and accessed them from your local machine by using their physical path or address in your browser. But how can you access those web pages from remote machines within a network? To make your web pages accessible from remote machines, you need to use server software known as a "Web Server."

Server:

A server is software that operates on two key principles: request and response. There are various types of server software used in the industry, including:

  • Server Operating Systems (e.g., Windows Server, Linux, Solaris)

  • Database Servers (e.g., Oracle, SQL Server, MySQL)

  • Application Servers

  • Web Servers

For our purposes, we need a Web Server to provide access to our web pages for remote clients.

Need for a Web Server: This software takes requests (HTTP Requests) from clients in the form of a "URL (Uniform Resource Locator)" and then sends web pages as responses (HTTP Responses).

Available Web Server Software:
There are several Web Server software options available in the market, including:

  • Apache Web Server by Apache

  • Nginx Web Server by NGINX

  • IIS Web Server by Microsoft

  • GWS Web Server by Google

  • LiteSpeed Web Server by LiteSpeed Technologies

For ASP.NET applications, the most compatible and widely used Web Server is IIS Web Server by Microsoft.

IIS Web Server

  • IIS stands for Internet Information Services, which was previously known as Internet Information Server.

  • IIS is a web server made by Microsoft and highly compatible with ASP.NET and ASP.NET Core applications.

  • IIS is part of the Windows operating system and is usually installed with it. To see if IIS is installed on your machine, open any web browser and enter the following URL:

      http://localhost
    

    Note: If IIS is not installed on your machine, you will receive the following error:

      HTTP Error 404. The requested resource is not found.
    

Installing IIS on Your Machine (If Not Already Installed):

  1. Go to the Control Panel on your computer.

  2. Access Programs(Click on Programs).

  3. Access Programs and Features(Click on Programs and Features).

  4. Click on Turn Windows features on or off.

  5. A new window called Windows Features will open.

    In this window, locate and select the checkbox next to Internet Information Services (IIS).

    Make sure to expand IIS and select all the sub-items (checkboxes) under it.

  6. Click the OK button to install IIS on your machine.

    Once the installation is complete, restart your machine.

  7. Verify IIS Installation:

    • After your machine restarts, verify that IIS is working correctly by accessing it through your web browser using the appropriate URL (typically http://localhost).

Access a Web Page Using IIS:

When we install the IIS (Internet Information Services) Web Server on our machine, it provides us with an administrative console known as "IIS Manager." This can be launched by searching for "inetmgr" in the Windows search bar.

Once IIS Manager is opened, you’ll find a "Connections" panel on the left-hand side (LHS) of the window. In this panel, you'll see your computer name listed as the Server Name (in this case, the server name is DESKTOP-HOOMVQE because the computer's name is DESKTOP-HOOMVQE).

When you expand this node, you’ll see a section called "Sites." Under "Sites," there is a default website named "Default Web Site," which is automatically created when IIS is installed on your machine.

Web Site

A Web Site is a collection of Web Pages, and a Web Server is a collection of Web Sites. This means a Web Server can contain one or more Web Sites. By default, when IIS is installed on a machine, there will be one Website already created, named "Default Web Site".

If we want to access web pages through a web server, we have three different options

Option 1: Accessing Through the "Default Web Site"

The "Default Web Site" is already created under the IIS (Internet Information Services) web server. We can use this site to access our web pages by copying them to a folder linked with the website, specifically the "<OS Drive>:\inetpub\wwwroot" directory. Once the web pages are copied to this folder, they can be accessed through IIS using their "Virtual Path" from either a local or a remote machine.

A virtual path is a URL that links to a folder on a web server. It lets you access files or web pages on the server using a URL, instead of knowing the exact location of the file on the server. For example, instead of using a path like C:\inetpub\wwwroot\Login.html, you would use a virtual path like http://localhost/Login.html to access it through a web browser.

To test this, let's copy our Login.html file into this folder and then access it using the virtual path as follows:

localhost:

  • Definition: localhost is the name for the computer you are using.

  • Purpose: It lets you access services (like a web server) on your own computer without needing its IP address.

  • Usage: http://localhost/ always points to the computer you are on, whether you are accessing it locally or remotely.

<YourMachineName>:

  • Definition: <YourMachineName> is the network name of your computer.

  • Purpose: It lets other devices on the same network access services on your computer. It's useful for accessing your computer from other devices on the same network.

  • Usage: http://<YourMachineName>/... uses your computer's network name, allowing other devices on the network to find and access services on your computer.

Note: For every website created in IIS (Internet Information Services), there is an associated folder on the hard disk where all the web pages of that site should be placed. Currently, the "Default Web Site" is mapped to the "wwwroot" folder, which is why we placed our "Login.html" page in that folder.

To view the folder mapped to the "Default Web Site":

  1. Open the IIS Manager window.

  2. Right-click on Default Web Site.

  3. Select Manage Website.

  4. Click on Advanced Settings.

In the window that appears, you'll find the "Physical Path" property, which shows the folder mapped to this website.

Option 2: Accessing Web Pages through an Application or Virtual Directory under the Default Web Site

Instead of copying all the web pages into the “inetpub/wwwroot” folder, you can create an application or virtual directory under the "Default Web Site" in IIS (Internet Information Services) and map it to your physical folder where the web pages are stored, such as the "Batch" folder.

Steps to Create an Application or Virtual Directory:

  1. Open IIS Manager.

  2. Right-click on "Default Web Site".

  3. Select "Add Application" or "Add Virtual Directory".

  4. In the window that appears:

    • In the "Alias" textbox, enter a name of your choice.

    • In the "Physical Path" textbox, enter the physical path of your folder, for example, <drive>:\Batch.

  5. Following this process, create one application named "Site1" and one virtual directory named "Site2".

  6. Map both to the physical folder, for example, "MVC".

Accessing the Web Pages:

Once you have created the application and virtual directory, you can access the pages in the following ways:

Option 3: Accessing Web Pages by Creating a New Site in IIS

In this option, you create a new site under IIS, similar to the existing "Default Web Site," and map it to a physical folder. The key difference is that you can assign your own host name or domain name, just like “localhost” (the host name for the "Default Web Site"), or you can use the same host name ("localhost") and change the port number.

Creating a New Site by Changing the Port Number

  1. Add a New Site:

    • Right-click on the "Sites" node in the "Connections" panel in IIS Manager.

    • Select "Add Website". A new window will open.

  2. Configure the New Site:

    • In the "Site name" textbox, enter a name for your site (e.g., "NitSite1").

    • In the "Physical path" textbox, specify the location of your folder (e.g., <drive>:\Batch).

    • In the "Port" textbox, the default port is "80". Change it to a different port number, such as "90".

    • Click "OK" to create the new site.

  3. Access the Web Pages:

Creating a New Site by Changing the Host Name or Domain Name

  1. Add a New Site:

    • Right-click on the "Sites" node in the "Connections" panel in IIS Manager.

    • Select "Add Website". A new window will open.

  2. Configure the New Site:

    • In the "Site name" textbox, enter a name for your site (e.g., "NitSite2").

    • In the "Physical path" textbox, specify the location of your folder (e.g., <drive>:\Batch).

    • In the "Host Name" textbox, specify a host name or domain name (e.g., nitsite.com).

    • Click "OK" to create the new site.

  3. Update the Hosts File:

    • To use this website, you need to specify the host name in the "hosts" file, located in the C:\Windows\System32\drivers\etc\ directory.

    • Copy the "hosts" file to a different location (it cannot be edited in its original location).

    • Add the following line to the end of the file:

        127.0.0.1 nitsite.com
      
    • Save the file and copy it back to the C:\Windows\System32\drivers\etc\ folder.

  4. Access the Web Pages:

Summary of Created Items

  • 1 Application and 1 Virtual Directory under the "Default Web Site".

  • 2 Sites under the server with the names "NitSite1" and "NitSite2".

All of these will be present in the "IIS Manager" under the Connections panel.

Creating Dynamic Web Pages

Dynamic web pages are created based on a client's request, and their content changes according to the request. For example, a transaction report on a bank's website may vary depending on the selected dates and transaction values:

  • Starting Date: 01/04/2021

  • Ending Date: 31/03/2022

  • Transaction Value: >= 15000

  • Transaction Value: <= 30000 (Optional)

How to Create a Dynamic Web Page?

To create a dynamic web page, in addition to HTML, client-side scripting languages like JavaScript, and CSS, we also need server-side technologies. These technologies handle the logic and data processing required to generate dynamic content. Several server-side technologies are available for creating dynamic web pages, such as: ColdFusion, Perl, PHP, Classic ASP, JSP (JavaServer Pages), Servlets, ASP.NET, ASP.NET Core, Django

Here's how different combinations work:

  1. HTML => Creates static web pages.

  2. HTML + CSS => Creates static web pages with enhanced styling.

  3. HTML + CSS + JavaScript => Creates static web pages with interactive features.

  4. HTML + CSS + JavaScript + Server-Side Technologies => Creates dynamic web pages.

Server-Side Technologies and Their Programming Languages

Every server-side technology use a specific programming language to implement the logic:

  • ColdFusion => CFML (ColdFusion Markup Language)

  • Perl => Perl Script

  • PHP => PHP Script

  • Classic ASP => VBScript or JScript

  • JSP and Servlets => Java

  • ASP.NET & ASP.NET Core => .NET Languages

  • Django => Python

ASP.NET is further divided into two parts:

  1. ASP.NET Web Forms

  2. ASP.NET MVC


ASP.NET Web Forms:

  • ASP.NET Web Forms is an open-source server-side web application framework developed by Microsoft for creating dynamic web pages.

  • It is designed to help programmers create websites, web applications, and web services.

  • The first version of ASP.NET Web Forms was released on January 5, 2002, as part of the .NET Framework 1.0. It replaced Microsoft's Classic ASP technology.

  • The latest version of ASP.NET Web Forms is 4.8, released in October 2019. This is the final version because it has been replaced by ASP.NET Core.

  • ASP.NET Web Forms is built on the Common Language Runtime (CLR), allowing developers to write ASP.NET code using any .NET language. When coding an ASP.NET application, developers can use all the libraries of the .NET Framework. This lets them create web applications that take advantage of CLR features like type safety, inheritance, and object-oriented programming.

  • ASP.NET is a web development framework that provides all the tools needed to build high-quality web applications with minimal coding.

How to Create Dynamic Web Pages Using ASP.NET Web Forms

To create a dynamic web page using ASP.NET Web Forms, follow these steps:

  1. Page Creation:

    • Save the page with a .aspx extension. This page can include HTML, JavaScript, CSS, and ASP.NET code.
  2. Server-Side Logic:

    • Implement server-side logic in the page using ASP.NET code. You can use either of the following methods:
    <script language="language" runat="server">
    // Server-Side Logic (ASPX Code)
    </script>

or

    <% 
    // Server-Side Logic (ASPX Code) 
    %>
  • Specify the language attribute to choose the programming language (VB or C#). The default is VB.

  • Use the runat="server" attribute to indicate that the logic should be executed on the server. For the second approach, you don't need to specify runat.

  1. Extension Importance:

    The extension of a web page is very important when creating dynamic web pages. If the extension is ".html", the web server will not process the logic implemented by ASP.NET. To test this, write the following code in a notepad, save it as "Test.html", and access it through the web server.

    Right-click on Test.html and choose "View in Browser".

    • Save this as Test.html and access it from browser in any of the following ways::

      • http://localhost/Site1/Test.html Accessing thru Application created.

      • http://localhost/Site2/Test.html Accessing thru Virtual Directory created.

      • http://localhost:90/Test.html Accessing thru Site created with different Port No. 90

      • http://nitsite.com/Test.html Accessing thru Site created.

    • The server will send the HTML content as-is, without processing the ASP.NET code.

  2. Processing ASP.NET Code:

    • In the above case, even though the web page contains ASP.NET code, the web server did not process it because of the page extension. It sends the content of the page "as is" to the browser. When we request a ".html" page from any browser, the web server immediately sends the content of that page as a response without checking what is in the file. Therefore, the ASP.NET code we wrote in the file is not processed by the server but displayed directly in the browser.

    • Now, use the "Save As" option in Notepad and save "Test.html" as "Test.aspx" in the same folder, "ASP". When we access the page from the browser, we don’t see the code; instead, we see the result:

      Right-click on Test.aspx and choose "View in Browser".

    • http://localhost/Site1/Test.aspx

      http://localhost/Site2/Test.aspx

      http://localhost:90/Test.aspx

      http://nitsite.com/Test.aspx

    • When we request a ".aspx" page from a web browser, the web server opens the file, reads it line by line, and writes the HTML code "as is" into the output stream. If it finds any ASP.NET code, it processes that logic and writes the results into the output stream as HTML. After processing the whole page, the content in the output stream is sent to the browser as a response.

ASP.NET Renders HTML

Due to varying internet bandwidth, different operating systems, web browsers, and devices, it’s essential to stick with HTML as the standard markup language. In all server-side technologies, including ASP.NET, the web server processes the server-side logic and converts the result into HTML. This process is called rendering, and the generated HTML is sent to clients as a response.

What is the Default Language Used in the Creation of ASPX Pages?

The default language used in the creation of ASPX pages is VB.NET.

How to Use C# as the Language for Creating ASPX Pages

To use C# as the language for creating ASPX pages, you need to specify this in the "Page Directive" at the top of the page. The directive allows you to define the language for the page development using its Language attribute, as shown below:

<%@ Page Language="C#" %>

To test this, add the above statement to the top of your "Test.aspx" file. If you don't add semicolons ; to the end of certain statements, such as:

<% Response.Write(DateTime.Now.ToShortDateString()); %>
<% Response.Write(DateTime.Now.ToLongTimeString()); %>

You will get an error indicating that a semicolon is expected. Simply add a semicolon; at the end of these statements to resolve the issue.

What is a Directive?

A directive is an instruction for the web server. By using the Page directive, you tell the web server that this page is written in a specific language (e.g., "C#"). The web server will then use the right compiler to compile the page.

What is "Response" in the Above Code?

Response is an instance of a predefined class called HttpResponse. It is known as an intrinsic object. In addition to Response, there are seven other intrinsic objects in ASP.NET: Request, Server, Session, Application, Trace, User, and Cache. Each of these intrinsic objects is an instance of a specific class. For example:

  • Request is an instance of the HttpRequest class.

  • Response is an instance of the HttpResponse class.

  • Server is an instance of the HttpServerUtility class.

How Are Intrinsic Objects Accessible to ASPX Pages?

Intrinsic objects are accessible to ASPX pages through their parent class. After an ASPX page is compiled, it is converted into a class that internally inherits from a predefined class called Page. This class is defined in the System.Web.UI namespace of the Base Class Library (BCL). All the eight intrinsic objects (Request, Response, Server, Session, Application, Trace, User, and Cache) are inherited from the Page class and are thus available in our ASPX pages.

Coding Techniques in ASP.NET

ASP.NET supports two different coding techniques for creating web pages:

  • Inline Coding Technique
    In this technique, HTML, JavaScript, CSS, controls, and business logic (implemented using C# or VB) are all contained within a single file saved with the .aspx extension. The "Test.aspx" page we created earlier is an example of inline coding.

  • Code-Behind Technique
    In this technique, HTML, JavaScript, CSS, and controls are present in one file saved with the .aspx extension, while the business logic (implemented using C# or VB) is contained in a separate file. This file is saved with the extension .aspx.cs or .aspx.vb, depending on the programming language used.

    Out:-

Developing Web Pages Using Visual Studio:

  1. Create a New Project in Visual Studio:

    • Open Visual Studio and select the “Create a new project” option.

    • In the window that opens:

      • Choose “C#” from the All Languages dropdown list.

      • Choose “Windows” from the All Platforms dropdown list.

      • Choose “Web” from the All Project Types dropdown list.

    • Below, select ASP.NET Web Application (.NET Framework) and click “Next.”

    • In the new window, enter the Project Name as “FirstWebApp” and the Location as <drive>:\Practice.

    • Select the latest Framework Version and click “Create.”

    • A new window will appear. Choose the Empty project template and, on the right-hand side, select the Web Forms checkbox. Ensure all other checkboxes are unchecked.

    • Click “Create” to create and open the new project.

      or

      If you can't find Solution Explorer, press ctrl + alt + L or go to view > Solution Explorer.

  2. Understanding the Project Structure:

    • The newly created project is initially empty, with no web pages included.

    • In the Solution Explorer, you'll find two empty folders named App_Data, Controllers and Models. You can either delete these or leave them as they are.

    • You will also see three essential files:

      • Global.asax: Handles application-level events.

      • Packages.config: Manages the NuGet packages used by the project.

      • Web.config: Contains configuration settings for the web application.

Note: Every ASP.NET Web Application project is a collection of web pages, referred to as “Web Forms.”

  1. Adding a Web Form to the Project:

    • Since the project does not contain any Web Forms yet, you'll need to add one.

    • In the Solution Explorer, right-click on the project, select Add > New Item.

    • In the “Add New Item” window, choose Web Form.

    • The default name will be “WebForm1.aspx.” Change this to “First.aspx” and click the “Add” button.

  2. Understanding the Web Form Structure:

    • The new "First.aspx" page will have a Page Directive at the top of the page with attributes like Language, AutoEventWireup, CodeBehind, and Inherits.

    • Below the Page Directive, you'll see some basic HTML code containing <head> and <body> sections.

  3. Viewing the Code-Behind File:

    • To view the Code-Behind file associated with this Web Form, right-click on “First.aspx” in the document window and select “View Code.”

    • This will open the “First.aspx.cs” file, which contains a class named First that inherits from the Page class.

    • Notice that the First class is a partial class, meaning it is defined in multiple files:

      1. First.aspx.cs

      2. First.aspx.designer.cs

Note: By default, only the “First.aspx.cs” file is visible. To view the “First.aspx.designer.cs” file, expand the “First.aspx” node in the Solution Explorer. These designer files are auto-generated by Visual Studio, so you should avoid editing their content directly.

Writing Code in a WebForm

Since your page is created using the Code Behind model, you can implement your logic either in the “.aspx” file or the “.aspx.cs” file.

  1. Implementing Logic in the “.aspx” File:

    • To add logic directly in the “First.aspx” page, place the following code within the <div> tag located under the <body> tag:

        Server Date: <% Response.Write(DateTime.Now.ToShortDateString()); %> <br />
        Server Time: <% Response.Write(DateTime.Now.ToLongTimeString()); %>
      
    • Note: Press F5 or ctrl + F5 to run the web page. This will execute the page and display the output in the browser.

  2. Implementing Logic in the “.aspx.cs” File:

    • To add logic in the code-behind file, create another WebForm named “Second.aspx”.

    • In the “Second.aspx.cs” file, implement the following code within the Page_Load method:

        Response.Write($"Server Date: {DateTime.Now.ToShortDateString()}");
        Response.Write("<br />");
        Response.Write($"Server Time: {DateTime.Now.ToLongTimeString()}");
      

      Both file structure and code.

How Does a Web Application Run Under Visual Studio?

To run a web application, you need a web server. Visual Studio has a built-in web server called IIS Express for running web applications during development.

  • When you create a project like “FirstWebApp” in Visual Studio, it runs using IIS Express.

  • Visual Studio assigns a random port to each web application for IIS Express, and this port will be different for each project and computer.

  • To see the port assigned to your web application, run any Web Form in your project and check the URL in the browser’s address bar, which will look like this:

http://localhost:YourPort/First.aspx
http://localhost:YourPort/Second.aspx

Note: IIS Express is a "Development Web Server" meant for testing web applications during development. After development, you can host your web application on Local IIS, a remote IIS server, or a public server.

How to Host Your Web Application on Local IIS

Currently, your web application is running under IIS Express in Visual Studio, but you can also host it on Local IIS. To do this:

  1. Run Visual Studio as Administrator:

    • Close Visual Studio and reopen it in Administrator mode by right-clicking on the Visual Studio icon and selecting “Run as Administrator.”
  2. Configure the Project to Use Local IIS:

    • Open the Solution Explorer, right-click on your project, and select Properties.

    • In the Project Property Window, select the Web tab on the left-hand side.

    • Scroll down to the Servers section. You will see a Drop Down List control with IIS Express selected by default.

    • Change the selection in the drop-down list to Local IIS. The Project URL will automatically update to:

        http://localhost/FirstWebApp
      
    • Click the “Create Virtual Directory” button next to the Project URL textbox. This action creates an “Application” under the “Default Web Site” of Local IIS.

    • Click the Save button in the Visual Studio standard toolbar.

  3. Run the Application Using Local IIS:

    • After saving, your web application will now run through Local IIS, and the URLs for your web forms will be:

        http://localhost/FirstWebApp/First.aspx
        http://localhost/FirstWebApp/Second.aspx
      

Working with Web Forms

Every Web Form in an ASP.NET Web Application project has three views to work with:

  1. Source View

  2. Design View

  3. Code View

1. Source View

When a new Web Form is added, it displays the Source View by default, which corresponds to the .aspx file. This view is used for writing HTML, CSS, JavaScript, and all the logic for creating controls.

2. Design View

This is a visual representation of the Source View. Whatever is written in the Source View is displayed as output in the Design View, similar to how the output would appear in a browser. Because of this feature, Visual Studio IDE is known as a WYSIWYG (What You See Is What You Get) IDE. This view can also be used for designing UIs through a "Drag and Drop" feature.

Note: To navigate from "Source View" to "Design View," you can use the options at the bottom of the .aspx file: Design, Split, and Source. By default, it will be set to Source. Click on Design to switch to the Design View, or click on Split to see both views simultaneously.

3. Code View

This is the .aspx.cs file of the Web Form, used for implementing all business logic using the C# language.

ASP.NET Server Controls

In ASP.NET, UI design mainly uses ASP.NET Server Controls instead of HTML controls. These server controls have several benefits over standard HTML controls:

  1. State Management: HTML controls lose their values once the Web Page is submitted to the server, but ASP.NET Server Controls keep their values even after the page is submitted.

  2. C# Integration: HTML controls can't be accessed directly in C# code, but ASP.NET Server Controls can be accessed directly, allowing you to use IntelliSense, which shows the members of that control.

ASP.NET provides a variety of controls for designing UIs, all of which are predefined classes in our libraries, specifically under the System.Web.UI.WebControls namespace. ASP.NET Server Controls are categorized into several types:

  1. Standard Controls

  2. Data Controls

  3. Validation Controls

  4. Navigation Controls

  5. Login Controls

  6. Web Parts Controls

  7. Ajax Extension Controls

  8. Dynamic Data Controls

Note: Although many controls are developed using C#, they are rendered as HTML during page processing. The logic for rendering is implemented in a method called RenderControl, which is invoked by the ASP.NET Framework while processing the page.

To verify how ASP.NET Server Controls render HTML, you can add a new Web Form to an existing project (e.g., “FirstWebApp”), naming it “Fourth.aspx.” Write the following code under the <div> tag in the Source View:

Enter Name: <input name="txtName1" type="text" id="txtName1" />
<input type="submit" name="btnSubmit1" value="Save" id="btnSubmit1" /><br />
Enter Name: <asp:TextBox ID="txtName2" runat="server" />
<asp:Button ID="btnSubmit2" runat="server" Text="Save" />

When you run this page, you will see two TextBoxes and two Buttons.

Right-click on the browser and select the option View Page Source to display the source code of this page.

Notice that the ASP.NET Server Controls are also rendered in HTML format:

Enter Name: <input name="txtName1" type="text" id="txtName1" />
<input type="submit" name="btnSubmit1" value="Save" id="btnSubmit1" /><br />
Enter Name: <input name="txtName2" type="text" id="txtName2" />
<input type="submit" name="btnSubmit2" value="Save" id="btnSubmit2" />

Working with ASP.NET Server Controls

Every ASP.NET Server Control is associated with three key components:

  1. Properties

  2. Methods

  3. Events

  • Properties are attributes of a control that define its appearance. Examples include Width, Height, BackColor, ForeColor, BorderColor, BorderStyle, Font, etc.

  • Methods are actions performed by the control when invoked. Examples include Focus(), Clear(), etc.

  • Events represent moments when an action should be performed, such as the click of a button, the load of a page, or the TextChanged event of a TextBox.

Note: The parent class for all ASP.NET Server Controls is the Control class within the System.Web.UI namespace. This class contains all the common properties, methods, and events for ASP.NET Server Controls.

Placing an ASP.NET Server Control on a Web Form

To work with ASP.NET Server Controls, start by creating a new empty ASP.NET Web Application (.NET Framework) project. Name it ControlsDemo, select the Empty Project Template, check the Web Forms option, and uncheck all other checkboxes. Click the Create button. After creating the project, delete any existing folders, and then add a Web Form named ControlCreation.aspx. Remove the <div> tag that is inside the <form> tag.

Adding Controls: You can place controls on your Web Form using three different views:

  1. Design View: Go to the Design View of your Web Form. On the left-hand side, you will see a window called Toolbox (if you do not see it, go to View > click on Toolbox). Open it, and under the Standard Tab, you'll find a list of controls. Either double-click the Button control or drag and drop it onto the Design View. This action will automatically generate the required ASPX code to create the button. To view this code, switch to the Source View, where you will see something like this:

     <asp:Button ID="Button1" runat="server" Text="Button" />
    
  2. Source View: You can also manually write code to create controls, similar to what Visual Studio generates. To test this, add the following code beneath the existing Button1 in Source View:

     <asp:Button ID="Button2" runat="server" Text="Button" />
    

    Note: Every control placed on a Web Form is an instance of a specific control class. In this case, Button1 and Button2 are instances of the Button class.

  3. Code View: Controls can also be created programmatically in the Code View. To test this, go to the .aspx.cs file of your Web Form and write the following code in the Page_Load method:

     Button Button3 = new Button();
     Button3.ID = "Button3";
     Button3.Text = "Button";
     form1.Controls.Add(Button3);
    

    Note: When you run the Web Form, you will see all three buttons displayed in the browser.

Working with Properties of Controls:

Every ASP.NET Server Control has many properties that define how it looks. You can set these properties in three ways:

  1. **Using Design View:**In the Design View of the ControlCreation.aspx Web Form, select Button1 and press F4 or Ctrl + F4 or right-click on the control in the design view and go to properties. This opens the Properties Window on the right-hand side, listing all properties of Button1. You can modify properties like BackColor, BorderColor, BorderStyle, BorderWidth, FontSize, ForeColor, etc., and view the changes directly in the Design View. The changes you make here will automatically generate the corresponding code in the Source View. To verify, switch to the Source View and you'll see the updated code:

     <asp:Button ID="Button1" runat="server" Text="Button" BackColor="Yellow" BorderColor="Blue" 
     BorderStyle="Dotted" BorderWidth="5px" Font-Size="XX-Large" ForeColor="Red" />
    
  2. Using Source View: Similar to Visual Studio generating code for Button1, you can manually write code to set properties for Button2. The Source View code should now look like this:

     <asp:Button ID="Button2" runat="server" Text="Button" BackColor="Yellow" BorderColor="Blue"
     BorderStyle="Dashed" BorderWidth="5px" Font-Size="XX-Large" ForeColor="Red" />
    
  3. Using Code View: You can also set properties programmatically in the .aspx.cs file. To test this, add the following code in the Page_Load method above the form1.Controls.Add(Button3); line:

     Button3.BackColor = System.Drawing.Color.Yellow;
     Button3.BorderColor = System.Drawing.Color.Blue;
     Button3.BorderStyle = BorderStyle.Double;
     Button3.BorderWidth = Unit.Pixel(5);
     Button3.Font.Size = FontUnit.XXLarge;
     Button3.ForeColor = System.Drawing.Color.Red;
    

    Note: Run the web page again to see the changes.

Working with Events of Controls

An Event is a moment in time when an action should be performed, such as executing a method. Every control is associated with a set of events that trigger based on user interactions. You can bind methods to these events so that the methods execute when the event is triggered.

Note: In GUI (Graphical User Interface) programming, we don’t call methods directly. Instead, we bind methods to events, and these methods execute whenever the event fires. Every event will fire at some point. Events are already defined under the Control classes, so we need to define methods in our page class and then bind those methods to events.

Defining Methods for Events in ASP.NET

You can define methods for events in three different ways:

  1. Using Design View:

    • Go to the Design View of ControlCreation.aspx.

    • Select Button1 and press F4 to open the Properties window.

    • In Properties window, click on the Events icon at the top. This will show the events linked to the button. Each event will trigger at a specific time, as described.

    • Double-click on the Click event. This action will generate a method in the .aspx.cs file for handling the logic to be executed when the end user clicks the button. The method will be named Button1_Click, following the pattern <ControlName>_<EventName>.

    • Now, write the following code in the Button1_Click method:

        Response.Write("<script>alert('Button1 is clicked.')</script>");
      
    • Note: If you go to the Source View, you'll see that the Button1_Click method is now bound to the button's click event, as shown below:

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
      
  2. Using Source View:

    • You can also generate event methods through the Source View. To do this, go to the Source View and add the following code to the end of the Button2 tag:

        OnClick="Button2_Click"
      
    • Note: When you type OnClick=, IntelliSense will display the option <Create New Event>. Select it, and Visual Studio will automatically generate the method. Now, in the Code View, you'll find the Button2_Click method where you can implement the logic. Write the following code in the Button2_Click method:

        Response.Write("<script>alert('Button2 is clicked.')</script>");
      
  3. Using Code View:

    • You can generate event methods in the Code View as well. To do this, go to the Page_Load method and type the following statement above the line form1.Controls.Add(Button3);:

        Button3.Click += Button3_Click;
      
    • Press the Tab key after typing Button3.Click +=, and Visual Studio will automatically generate the Button3_Click method. Write the following code inside this method:

        Response.Write("<script>alert('Button3 is clicked.')</script>");
      

Note: The methods where you implement the logic for an event are known as Event Procedures or Event Handlers. These methods are non-value returning (void) and always take two parameters:

  1. sender of type Object

  2. e of type EventArgs or a subclass of EventArgs

Default Events

Every control is associated with multiple events, and you can generate an Event Handler for any of these events using one of the three methods described above. However, each control has a default event. To generate an Event Handler for the default event without using any of the methods described above, you can simply double-click on the control in the Design View, and Visual Studio will automatically generate the required Event Handler.

Here is a list of some controls and their default events:

ControlDefault Event
Button, LinkButton, ImageButtonClick
TextBoxTextChanged
CheckBox and RadioButtonCheckedChanged
DropDownList, ListBox, CheckBoxList, RadioButtonListSelectedIndexChanged
CalendarSelectionChanged

Label Control

  • The Label control is used for displaying static text on the UI, and the text is set using the Text property of the control.

Button Control:

  • The Button control is designed for submitting a page to the server. There are three classes (controls) within this family: Button, LinkButton, and ImageButton. When any of these buttons are placed on a Web Form, they render the following corresponding HTML code:

    • Button => <input type="submit" />

    • LinkButton => <a href="javascript:__doPostBack()">

    • ImageButton => <input type="image" />

Note: To use an ImageButton, you need to set the ImageUrl property. To do this, open the Solution Explorer, right-click on the project, select Add > New Folder to add a new folder to the project, and name it Images. Right-click on the Images folder, select Add > Existing Item, and choose an image from your hard disk to add it to the folder.

To work with the Button controls, add a new Web Form to the project, naming it ButtonDemo1.aspx, and add the following code inside the <div> tag:

<asp:Button ID="btnClick1" runat="server" Text="Click Me" />
<asp:LinkButton ID="btnClick2" runat="server" Text="Click Me" />
<asp:ImageButton ID="btnClick3" runat="server" ImageUrl="~/Images/Image.jpg" Width="50" Height="50" />

When you run the page, it will render the following HTML code, which you can view using the View Page Source option in the browser:

<input type="submit" name="btnClick1" value="Click Me" id="btnClick1" />
<a id="btnClick2" href="javascript:__doPostBack('btnClick2','')">Click Me</a>
<input type="image" name="btnClick3" id="btnClick3" src="Images/Image.jpg" style="height:50px;width:50px;" />

What is meant by submitting a page to the server?

Submitting a page to the server means sending all the values from the controls on a page from the user's browser to the web server.

Page Submission Types:

  1. Postback Submission: The process of submitting a page back to itself.

  2. Cross-Page Submission: The process of submitting a page to another page.

Page1 => Submitting to Page1 ( Postback Submission)
Page1 => Submitting to Page2 (Cross-Page Submission)

Note: By default, the Button control submits a page back to itself (Postback), but it can also submit the page to other pages (Cross-Page).

Understanding Postback Submission and Cross-Page Submission:

Add a new Web Form to your project and name it ButtonDemo2.aspx. Add the following code inside the <div> tag:

<asp:Button ID="Button1" runat="server" Text="Postback Submission" />
<asp:Button ID="Button2" runat="server" Text="Crosspage Submission" />

Initially, both buttons will perform Postback Submission only. To verify this, go to the ButtonDemo2.aspx.cs file and add the following code inside the Page_Load event handler:

if (IsPostBack)
    Response.Write("This is a post or post back request.");
else
    Response.Write("This is a first or get request.");

Note: IsPostBack is a property of the Page class that returns true if the current request is a Postback request and false if it is the first (Get) request. The first request to a page is called a "Get Request," and later requests are called "Post Requests.".

Now, run the Web Form. Initially, the output will display the message This is a first or get request. indicating that it is the first request. When you click on either of the two buttons, the message will change to This is a post or post back request indicating a Postback request.

Currently, both buttons are performing Postback Submission. To make the second button perform Cross-Page Submission, add a new Web Form to the project and name it ButtonDemo3.aspx. Add the following code inside the Page_Load event handler in the Code View:

Response.Write("<font color='red'>Cross Page Submission.</font>");

Next, go to the Design View of ButtonDemo2.aspx, select the second button, and go to its properties. Find the PostBackUrl property, click the button next to it (...), and select ButtonDemo3.aspx. Now, run the ButtonDemo2.aspx form. When you click on Button1, it will perform Postback Submission. When you click on Button2, it will perform Cross-Page Submission and launch ButtonDemo3.aspx.

Important Members of the Button Control

  1. Text: This property allows you to associate text with the control that is visible to end users. It acts as the caption of the button.

  2. PostBackUrl: This property allows you to specify the address of the target page to which the current page should be submitted when the button is clicked.

  3. OnClientClick: This property allows you to specify the name of a JavaScript function that should be executed when the button is clicked, i.e., before the page is submitted to the server.

  4. CommandName & CommandArgument: These properties let you add extra data to the button, besides the Text property. This data is not visible to users but can be used in the Command event code.

  5. Click: This is an event that fires when the button is clicked.

  6. Command: This event fires when the button is clicked, and there are associated CommandName or CommandArgument values.

Example to Understand the OnClientClick Property:

To understand the OnClientClick property, add a new Web Form to the project named ButtonDemo4.aspx and write the following code under its <div> tag:

<asp:Button ID="Button1" runat="server" Text="Click Me" />
<asp:Label ID="Label1" runat="server" ForeColor="Red" />

In this Web Form, when the button is clicked, it should display a message in the Label control indicating that the page has been submitted to the server. To achieve this, generate a Click event handler for the Button control and write the following code in it:

Label1.Text = "Page is submitted to server.";

Now, when you run the form and click on the Button control, the Label control will display the message. However, before submitting the page to the server, the user should be asked for confirmation. If the user confirms, only then should the page be submitted. This can be achieved using JavaScript. To do this, go to the Source View of ButtonDemo4.aspx and write the following code under the <head> section of the page:

<script>
function Confirmation() {
    var Result = confirm("Are you sure you want to submit the page to the server?");
    return Result;
}
</script>

To execute this code when the Button is clicked, go to the Design View of the page, select the Button, go to its properties, select the OnClientClick property, and type the name of the JavaScript function as follows: "return Confirmation()". Now, run the Web Form again and check the output.

Understanding the object sender and EventArgs Parameters in Event Handlers:

As discussed earlier, every event handler takes two parameters: sender of type object and e of type EventArgs or a child class of EventArgs. These parameters are useful for implementing logic for multiple controls in a single event handler.

  1. object sender: To understand this parameter, add a new Web Form to the project named Calculator1.aspx and write the following code in its <div> tag:
<table align="center">
    <caption>Calculator</caption>
    <tr>
        <td>Enter 1<sup>st</sup> number:</td>
        <td><asp:TextBox ID="txtNum1" runat="server" /></td>
    </tr>
    <tr>
        <td>Enter 2<sup>nd</sup> number:</td>
        <td><asp:TextBox ID="txtNum2" runat="server" /></td>
    </tr>
    <tr>
        <td>Result:</td>
        <td><asp:TextBox ID="txtResult" runat="server" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnAdd" runat="server" Text="Add" />
            <asp:Button ID="btnSub" runat="server" Text="Sub" />
            <asp:Button ID="btnMul" runat="server" Text="Mul" />
            <asp:Button ID="btnDiv" runat="server" Text="Div" />
            <asp:Button ID="btnMod" runat="server" Text="Mod" />
        </td>
    </tr>
</table>

Let's write one event handler method for all five buttons. To do this, go to the Design View of the form, select the "Add" button, open the property window, select Events, and in the Click event, specify the name for the event handler as Buttons_Click, then click on it. This will generate the event handler with the given name.

Now, to bind the event handler with the remaining four buttons, go back to the Design View, select the "Sub", "Mul", "Div", and "Mod" buttons simultaneously, open the property window, select Events, and in the Click event, you will see a dropdown beside it. Click on the dropdown, and you will see the event handler Buttons_Click in the list. Select it to bind the event handler to all four buttons.

Now go to “Calculator1.aspx.cs” file and write the below code over there:

//Calculator1.aspx.cs
protected void bnttons_Click(object sender, EventArgs e)
{
    int result = 0;
    if (!IsPostBack)
    {
        txtNum1.Focus();
    }

    Button b = (Button)sender;
    //Or
    //Button b = sender as Button;
    int num1 = int.Parse(txtNum1.Text);
    int num2 = int.Parse(txtNum2.Text);

    switch (b.ID)
    {
        case "btnAdd":
            result =  num1 + num2;
            break;
        case "btnSub":
            result = num1 - num2;
            break;
        case "btnMul":
            result = num1 * num2;
            break;
        case "btnDiv":
            result = num1 / num2;
            break;
        case "btnMod":
            result = num1 % num2;
            break;
    }
    txtResult.Text = result.ToString();
}

When an event handler is linked to multiple controls, we can identify which control triggered the event (like a click) using the "sender" parameter of the event handler. Each control on the form is an instance of a class. When a control instance triggers an event, that instance is captured in the "sender" parameter, which is of type "object" (the default parent class of all classes).

Since "sender" is of type "object," it can't access any child class members directly. For example, in the code above, "Button" is the child class. To solve this, we need to convert "sender" back into a Button, as shown in the code. Then, we can read its ID, Text, or any other property and apply the specific logic for that control.

Note's: The line Button b = (Button)sender; or Button b = sender as Button; is used to change the sender object, which is of type object, into a Button type.

  • Button b = (Button)sender;: This is an explicit cast. It changes sender to Button. If sender is not a Button, it will throw an exception.

  • Button b = sender as Button;: This is a safe cast. It tries to change sender to Button. If sender is not a Button, b will be null instead of throwing an exception.

Both lines let you access the properties and methods specific to the Button class after the conversion.


Understanding the EventArgs (or Child Class of EventArgs) Parameter

To understand the EventArgs parameter, add a new Web Form to the project named Calculator2.aspx and write the following code in its <div> tag:

<table align="center">
    <caption>Calculator</caption>
    <tr>
        <td>Enter 1<sup>st</sup> number:</td>
        <td><asp:TextBox ID="txtNum1" runat="server" /></td>
    </tr>
    <tr>
        <td>Enter 2<sup>nd</sup> number:</td>
        <td><asp:TextBox ID="txtNum2" runat="server" /></td>
    </tr>
    <tr>
        <td>Result:</td>
        <td><asp:TextBox ID="txtResult" runat="server" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnAdd" runat="server" Text="Add" CommandName="+" />
            <asp:Button ID="btnSub" runat="server" Text="Sub" CommandName="-" />
            <asp:Button ID="btnMul" runat="server" Text="Mul" CommandName="*" />
            <asp:Button ID="btnDiv" runat="server" Text="Div" CommandName="/" />
            <asp:Button ID="btnMod" runat="server" Text="Mod" CommandName="%" />
        </td>
    </tr>
</table>

In the above example, we have set a CommandName property for each button. This value can be accessed and used in the Command event of the button.

Let's write one event handler method for all five buttons. To do this, go to the design view of the form, select the Add button, open the property window, select Events, then select the Command event. Next to the event, specify a name for the event handler (e.g., Buttons_Command) and click on it, which will generate an event handler with the given name.

To bind the event handler to the remaining four buttons, go back to the design view, select the Sub, Mul, Div, and Mod buttons simultaneously, open the property window, select Events, and under the Command event, you will see a dropdown. Click on the dropdown, select the Buttons_Command event handler, which will bind the event handler to all four buttons.

Now, go to the Calculator2.aspx.cs file and write the following code:

Code under Page_Load:

if (!IsPostBack)
{
    txtNum1.Focus();
}

Code under Buttons_Command:

int Num1 = int.Parse(txtNum1.Text);
int Num2 = int.Parse(txtNum2.Text);
int Num3 = 0;

switch(e.CommandName)
{
    case "+":
        Num3 = Num1 + Num2;
        break;
    case "-":
        Num3 = Num1 - Num2;
        break;
    case "*":
        Num3 = Num1 * Num2;
        break;
    case "/":
        Num3 = Num1 / Num2;
        break;
    case "%":
        Num3 = Num1 % Num2;
        break;
}
txtResult.Text = Num3.ToString();

In this case, we have set a CommandName for each button, and we can get that CommandName value in the event handler using the e parameter of type CommandEventArgs (a child class of EventArgs). Once we get the CommandName, we can easily identify which control is raising the event and implement the logic as shown in the code above.

Note: Similar to CommandName, we can also use the CommandArgument property. However, CommandName is of type string, while CommandArgument is of type object. Both of these properties can only be accessed within the Command event.


TextBox Control

The TextBox control is used to accept input from users, and it can be used in 16 different ways, such as Single Line Text, Multi-Line Text, Password, etc.

Important members of TextBox Control:

  1. TextMode: This property sets the behavior of the control and can be assigned any of the following values:

    • SingleLine: For a single line of text (default).

    • MultiLine: For multiple lines of text.

    • Password: For entering a password (hides the characters).

    • Date: For selecting a date.

    • DateTime: For selecting a date and time.

    • DateTimeLocal: For selecting a local date and time.

    • Time: For selecting a time.

    • Month: For selecting a month.

    • Week: For selecting a week.

    • Number: For entering a number.

    • Range: For entering a range of values.

    • Color: For selecting a color.

    • URL: For entering a URL.

    • Email: For entering an email address.

    • Phone: For entering a phone number.

    • Search: For entering a search query.

  2. ReadOnly: This Boolean property has a default value of false. When set to true, the control becomes non-editable (read-only), meaning users can see the text but cannot modify it.

  3. Rows: This property specifies the number of display rows when the TextMode is set to MultiLine.

  4. MaxLength: This property specifies the maximum number of characters that can be entered into the TextBox control.

  5. AutoPostBack: This Boolean property has a default value of false. When set to true, the control automatically submits the page to the server when the content of the TextBox changes (i.e., it triggers a postback).

  6. TextChanged: This is the default event of the control. It fires when the content of the Text property has changed.

TextChanged Event:

To work with the TextChanged event of the TextBox, follow these steps:

  1. Add a New Web Form:

    • Add a new WebForm to your project and name it ColorDialog.aspx

    • Replace the existing <div> tag with the following code under the <form> tag:

    <div id="div1" runat="server">
        <br />Change Color: <asp:TextBox ID="txtColor1" runat="server" TextMode="Color" />
        <br /><br />
    </div>
    <asp:Button ID="Button1" runat="server" Text="Button" />
  1. Generate the TextChanged Event Handler:

    • Go to the Design view of the WebForm.

    • Double-click on the TextBox control to generate a TextChanged event handler.

    • In the aspx.cs file, write the following code inside the txtColor1_TextChanged event handler:

    protected void txtColor1_TextChanged(object sender, EventArgs e)
    {
        div1.Attributes.Add("style", "background-color:" + txtColor1.Text);
    }
  1. Test the Web Form:

    • Run the Web Form.

    • Select a color using the Color Dialog in the TextBox.

    • However, notice that the background color of the <div> control does not change immediately, even though the logic is implemented under the TextChanged event of the TextBox.

Explanation:

  • The TextBox control cannot automatically submit the page to the server. Because of this, the logic in the TextChanged event handler will not run until the page is submitted.

    When you select a color using the TextBox, the color does not change immediately because the TextBox does not automatically submit the page to the server. However, when you click the Button, the page is submitted to the server, and the color change logic inside the TextChanged event handler is executed. This happens because the Button triggers a postback, which causes all events, including those from the TextBox, to be processed.

  • To test this, after selecting a color in the Color Dialog, click the Button below the TextBox. The page will be submitted to the server, and the logic in the TextChanged event will then run.

Why Does the Logic Execute When the Button is Clicked?

  • When a control raises an event but is not capable of submitting the page to the server, the event gets cached. This means the event is stored and will execute when the page is next submitted to the server. These are known as "Cached Events."

  • Cached Events: These events store the page data, which is then processed when the page is submitted to the server through a postback.

Immediate Execution of Logic Without Button Click

If you want the logic to execute immediately after changing the color, without waiting for the Button click, follow these steps:

  1. Delete the Button:

    • Delete the Button control from the form.
  2. Enable AutoPostBack:

    • Set the AutoPostBack property of the TextBox control to true. This will give the control the ability to submit the page to the server immediately when the Text (Color) is changed.
    <asp:TextBox ID="txtColor1" runat="server" TextMode="Color" AutoPostBack="true" />

With AutoPostBack set to true, the page will automatically submit to the server as soon as the color is selected, and the background color of the <div> will change immediately.

Understanding Page Submission

The process of sending the values entered by a user in the controls of a page to the Web Server is known as Page Submission. It can be of two types:

  1. **Postback Submission: Submitted the data back to itself,**In a Postback Submission, we can read the values of controls directly on the server using their properties.

  2. Cross Page Submission: Sending data from one page to another page.

Postback Submission

To understand Postback Submission in detail, let’s create a simple Login Form.

  1. Create the Login Form:

    • Add a new WebForm to your project and name it LoginForm.aspx

    • Write the following code inside the <div> tag to create the login form layout:

    <table align="center">
        <caption>Login Form</caption>
        <tr>
            <td>Enter Name:</td>
            <td><asp:TextBox ID="txtName" runat="server" /></td>
        </tr>
        <tr>
            <td>Enter Password:</td>
            <td><asp:TextBox ID="txtPwd" runat="server" TextMode="Password" MaxLength="16" /></td>
        </tr>
        <tr>
            <td>Enter Email:</td>
            <td><asp:TextBox ID="txtEmail" runat="server" TextMode="Email" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
                <asp:Button ID="btnReset" runat="server" Text="Reset" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Label ID="lblStatus" runat="server" ForeColor="Red" />
            </td>
        </tr>
    </table>
  1. Generate Event Handlers:

    • In the Design view, double-click on the "Submit" button (btnSubmit) and the "Reset" button (btnReset) to generate the required event handlers.
  2. Write the Code for Event Handlers:

    • In the LoginForm.aspx.cs file, implement the following code:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtName.Focus();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (txtName.Text == "admin" && txtPwd.Text == "admin#123" && txtEmail.Text == "admin@nareshit.com")
        {
            lblStatus.Text = "Valid User";
        }
        else
        {
            lblStatus.Text = "Invalid User";
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        txtName.Text = "";
        txtPwd.Text = "";
        txtEmail.Text = "";
        txtName.Focus();
    }
  1. Explanation of Postback Submission:

    • In the above page, we performed a Postback Submission, meaning the page submitted the data back to itself for validation. In a Postback Submission, we can read the values of controls directly on the server using their properties. For example, in our code, we read the value of the TextBox using its Text property.

Cross Page Submission

Cross Page Submission means sending data from one page to another page. Let's understand this with an example.

  1. Creating the Forms:

    • Add two new WebForms to your project named Contact.aspx and Respond.aspx.

    • In Contact.aspx, write the following code inside the <div> tag to create a contact form:

    <table align="center">
        <caption>Contact Details</caption>
        <tr>
            <td>Name:</td>
            <td><asp:TextBox ID="txtName" runat="server" /></td>
        </tr>
        <tr>
            <td>Phone No:</td>
            <td><asp:TextBox ID="txtPhone" runat="server" MaxLength="10" /></td>
        </tr>
        <tr>
            <td>Email Id:</td>
            <td><asp:TextBox ID="txtEmail" runat="server" TextMode="Email" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" PostBackUrl="~/Respond.aspx" />   
                <asp:Button ID="btnReset" runat="server" Text="Reset" />
            </td>
        </tr>
    </table>
  1. Generating Event Handlers:

    • In the Design view, double-click on the "Reset" button (btnReset) to generate the event handler.

    • In the Contact.aspx.cs file, add the following code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtName.Focus();
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        txtName.Text = "";
        txtPhone.Text = "";
        txtEmail.Text = "";
        txtName.Focus();
    }
  1. Testing Cross Page Submission:

    • Run Contact.aspx, fill in the details, and click the "Submit" button.

    • Since the PostBackUrl property of the "Submit" button is set to Respond.aspx, the data will be sent from Contact.aspx to Respond.aspx, performing a Cross Page Submission, because of PostBackUrl="~/Respond.aspx".

  2. In the process of "Cross Page Submission," all values entered into the controls on the "Contact.aspx" page will be sent to the "Respond.aspx" page. During this, a lot of information is transferred from the browser to the server, such as Session State, Application State, Request Cookies, Response Cookies, Headers, Form Data, Query Strings, and Server Variables.

    Form Collection will have the information of controls and their values in a "name/value" pair. So, on the "Respond.aspx" page, we can read Form Collection values using the "name" with the request object and use their values.

  3. Handling Data on Respond.aspx:

    • In Respond.aspx.cs, write the following code inside the Page_Load method to retrieve the data:
    protected void Page_Load(object sender, EventArgs e)
    {
        string Name = Request.Form["txtName"];
        string Phone = Request.Form["txtPhone"];
        string Email = Request.Form["txtEmail"];
        Response.Write($"<h3>Hello {Name}, we have received your contact details.</h3>");
        Response.Write($"Contact Phone: {Phone}<br />");
        Response.Write($"Contact Email: {Email}<br />");
    }
  • Here, Request.Form refers to the Form Collection, and the parameters passed correspond to the ID of the controls in Contact.aspx.

    Note: In the above code, "Request.Form" refers to the "Form Collection," and the parameter we pass to it is the "name" of the value we want to read.

  1. Understanding Submit Methods:

    • When data is submitted from one page to another, the transfer occurs via either the Get method or the Post method.

    • For HTML forms, the default method is get. For ASPX forms, the default is post.

    • If you want to change the submission method in Contact.aspx, you can modify the <form> tag as follows:

    <form id="form1" runat="server" method="get">
  • Now, when you run Contact.aspx and submit the form, the data will be sent as a Query String, and you should modify Respond.aspx.cs to retrieve data using Request.QueryString:
    string Name = Request.QueryString["txtName"];
    string Phone = Request.QueryString["txtPhone"];
    string Email = Request.QueryString["txtEmail"];

Currently, "Contact.aspx" uses an ASPX form, so the submit method is "post".

  1. Difference between Get and Post:

    • Get Method:

      • Data is concatenated to the URL in the form of a Query String and is visible in the browser's address bar.

      • Faster but less secure; not recommended for sensitive information.

      • Limited to a maximum URL length of 2048 characters.

      • Data is accessed from the QueryString collection.

      • string Email = Request.QueryString[];

    • Post Method:

      • Data is passed through HTTP headers, not visible to the user.

      • More secure and suitable for sensitive information.

      • No size limitations for data transfer.

      • Data is accessed from the Form collection.

      • string Email = Request.Form[]

  2. Specifying Target URL in Cross Page Submission:

    • We specified the target page URL for "Cross Page Submission" using the "PostBackUrl" property of the Button. In other web technologies, we use the "action" attribute of the form for this. You can do the same in ASP.NET. To test this, delete the "PostBackUrl" property from the "Submit" Button, then go to the "<form>" tag and add the action attribute to it. It should now look like this:
    <form id="form1" runat="server" method="get" action="Respond.aspx">
  • Run the page again and notice that when we click the "Submit" button, the page will be sent to "Respond.aspx". The problem with this approach is that both the "Submit" and "Reset" buttons will cause the page to be submitted. To avoid this, we use the button's "PostBackUrl" attribute instead of the form's "action" attribute. This way, the "Submit" button performs "Cross Page Submission" and the "Reset" button performs "Postback Submission".

Transferring Control between Pages

You can transfer control from one page to another in a web application using either Server.Transfer or Response.Redirect.

  1. Create the Pages:

    • Add three new WebForms to your project: LoginPage.aspx, SuccessPage.aspx, and FailurePage.aspx.
  2. Designing the LoginPage.aspx:

    • Define a style for the <body> tag and write the following code inside the <div> tag:
    <table align="center">
        <caption>Login Page</caption>
        <tr>
            <td>User Name:</td>
            <td><asp:TextBox ID="txtName" runat="server" /></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><asp:TextBox ID="txtPwd" runat="server" TextMode="Password" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnReset" runat="server" Text="Reset" />
                <asp:Button ID="btnLogin" runat="server" Text="Login" />
            </td>
        </tr>
    </table>
  1. Generating Event Handlers:

    • Generate Click Event Handlers for the "Login" and "Reset" buttons, and add the following code in LoginPage.aspx.cs:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtName.Focus();
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        txtName.Text = "";
        txtPwd.Text = "";
        txtName.Focus();
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (txtName.Text == "Codecomponents" && txtPwd.Text == "1234")
        {
            Server.Transfer("SuccessPage.aspx");
        }
        else
        {
            Response.Redirect("FailurePage.aspx");
        }
    }
  1. Setting Styles for SuccessPage.aspx and FailurePage.aspx:

    • In SuccessPage.aspx, set the <body> style to:
    <body style="background-color:deepskyblue">
  • In FailurePage.aspx, set the <body> style to:
    <body style="background-color:gold">
  1. Testing the Transfer:

    • Run LoginPage.aspx, enter valid credentials, and click the "Login" button. You'll be taken to SuccessPage.aspx.

    • If invalid credentials are entered, clicking the "Login" button will take you to FailurePage.aspx.

Understande Server T

Server.Transfer

In this case, the transfer between source and target pages happens only on the server. When we enter valid credentials and click the Login button, it first goes to "LoginPage" because it is a "Postback." Then, "Server.Transfer" moves the control to "SuccessPage" as follows:

  • Explanation:

    • Server.Transfer moves control from one page to another on the server side without involving the client. This means the URL in the browser's address bar stays the same.

    • When valid credentials are entered and the "Login" button is clicked, the request first goes to LoginPage.aspx as part of a postback. Then, Server.Transfer moves control directly to SuccessPage.aspx on the server. The browser doesn't know about this transfer since no new request is made.

  • Process Flow:

    1. User submits valid credentials.

    2. A postback occurs, and the request is sent to LoginPage.aspx.

    3. On the server, Server.Transfer is called, which directly transfers the request to SuccessPage.aspx.

    4. SuccessPage.aspx is processed, and the response is sent back to the client.

Key Point: The URL in the browser's address bar still shows LoginPage.aspx, even though the content from SuccessPage.aspx is being displayed.

Response.Redirect

In this case, the transfer between source and target pages happens through the browser. When we enter invalid credentials and click the Login button, it first goes to "LoginPage" because it is a "PostBack." Then, "Response.Redirect" sends a 302 response to the browser, asking it to make a new request to the server for "FailurePage." The browser then requests "FailurePage" from the server and receives the page as a response, as follows:

  • Explanation:

    • Response.Redirect involves the browser in the page transfer process. When invalid credentials are entered and the "Login" button is clicked, the request first goes to LoginPage.aspx. Then, Response.Redirect sends an HTTP 302 response to the browser, telling it to make a new request to FailurePage.aspx.

    • This updates the browser's address bar to show the URL of FailurePage.aspx.

  • Process Flow:

    1. User submits invalid credentials.

    2. A postback occurs, and the request is sent to LoginPage.aspx.

    3. On the server, Response.Redirect is called, which sends a 302 redirect response to the browser.

    4. The browser gets the 302 response and makes a new request to the server for FailurePage.aspx.

    5. The server processes FailurePage.aspx and sends the response back to the client.

Key Point: The URL in the browser's address bar changes to FailurePage.aspx, showing the new page being requested.

Differences between Server.Transfer and Response.Redirect

  1. Transfer Mechanism: In the case of Server.Transfer, the transfer between pages happens directly on the web server itself. In the case of Response.Redirect, the transfer between pages is done by the browser.

  2. Performance: Server.Transfer is faster because it doesn't need extra round trips between the browser and server. On the other hand, Response.Redirect requires extra round trips, making it slower.

  3. URL in Address Bar: In the case of Server.Transfer, the URL in the browser's address bar does not update to the new page's address, so we can't bookmark the page. However, with Response.Redirect, the URL does update, allowing us to bookmark the page.

  4. Scope of Transfer: With Server.Transfer, we can only transfer to pages on the same site. With Response.Redirect, we can transfer to pages on the same site, other sites on the same server, and even other servers.

RadioButton and CheckBox Controls Example

We use these controls to give users a list of values to choose from. Radio Buttons are for single selection, and Checkboxes are for multiple selections. Both Radio Buttons and Checkboxes have a boolean property called "Checked" that tells us if the control is selected (true) or not (false).

Note: For Radio Buttons, we need to specify how many buttons are in a group using the "Group Name" attribute. This way, only one Radio Button can be selected in each group.

To use Checkboxes and Radio Buttons, add a new WebForm to your project named "RadioAndCheck.aspx" and write the following code inside the "<div>" tag:

ASPX Code (RadioAndCheck.aspx):

<div>
    Name:
    <asp:TextBox ID="txtName" runat="server" /> <br />

    Gender:
    <asp:RadioButton GroupName="Gender" ID="rbMale" runat="server" Text="Male" />
    <asp:RadioButton GroupName="Gender" ID="rbFemale" runat="server" Text="Female" />
    <asp:RadioButton GroupName="Gender" ID="rbTrans" runat="server" Text="Transgender" /> <br />

    Eating Habit:
    <asp:RadioButton GroupName="Habit" ID="rbVeg" runat="server" Text="Vegetarian" />
    <asp:RadioButton GroupName="Habit" ID="rbNonVeg" runat="server" Text="Non-Vegetarian" />
    <asp:RadioButton GroupName="Habit" ID="rbVegan" runat="server" Text="Vegan" /> <br />

    Hobbies:
    <asp:CheckBox ID="cbReading" runat="server" Text="Reading Books" />
    <asp:CheckBox ID="cbPlaying" runat="server" Text="Playing Games" />
    <asp:CheckBox ID="cbWatching" runat="server" Text="Watching Movies" />
    <asp:CheckBox ID="cbPainting" runat="server" Text="Drawing & Painting" /> <br />

    <asp:Button ID="btnSubmit" runat="server" Text="Submit Values" OnClick="btnSubmit_Click" /> <br />
    <asp:Label ID="lblMsg" runat="server" ForeColor="Red" />
</div>

Now create a Click Event Handler for the "Display Values" button. Import the System.Text namespace and add the following code to the RadioAndCheck.aspx.cs file:

Code-Behind (RadioAndCheck.aspx.cs):

using System;
using System.Text;
using System.Collections.Generic;

public partial class RadioAndCheck : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtName.Focus();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        if (txtName.Text.Trim().Length > 0)
        {
            sb.Append($"Name: {txtName.Text}<br />");
        }

        if (rbMale.Checked)
        {
            sb.Append("Gender: Male<br />");
        }
        else if (rbFemale.Checked)
        {
            sb.Append("Gender: Female<br />");
        }
        else if (rbTrans.Checked)
        {
            sb.Append("Gender: Transgender<br />");
        }

        if (rbVeg.Checked)
        {
            sb.Append("Eating Habit: Vegetarian<br />");
        }
        else if (rbNonVeg.Checked)
        {
            sb.Append("Eating Habit: Non-Vegetarian<br />");
        }
        else if (rbVegan.Checked)
        {
            sb.Append("Eating Habit: Vegan<br />");
        }

        List<string> hobbies = new List<string>();

        if (cbPlaying.Checked)
        {
            hobbies.Add("Playing Games");
        }
        if (cbReading.Checked)
        {
            hobbies.Add("Reading Books");
        }
        if (cbWatching.Checked)
        {
            hobbies.Add("Watching Movies");
        }
        if (cbPainting.Checked)
        {
            hobbies.Add("Drawing & Painting");
        }

        if (hobbies.Count > 0)
        {
            sb.Append($"Hobbies: {string.Join(", ", hobbies)}");
        }

        lblMsg.Text = sb.ToString();
    }
}

List Controls

List Controls: These controls let users pick from a list of values. In ASP.NET Web Forms, we have 4 List Controls:

  1. DropDownList: Displays a single item by default, and only one item can be selected.

  2. ListBox: Displays multiple items by default, and allows for the selection of one or more items.

  3. RadioButtonList: Displays multiple items by default, but only one item can be selected.

  4. CheckBoxList: Displays multiple items by default, and allows for the selection of one or more items.

Properties of List Controls

To work with these controls, you first need to add values to them. Each value in a List Control is known as a ListItem (a class), and each value is an instance of this class. Every ListItem has four main attributes:

  • Text: The text displayed to the user (the "Display Member").

  • Value: The underlying value (the "Value Member") that is not visible to the user but is used in the backend logic.

  • Enabled: A Boolean property that is true by default. If set to false, the ListItem will be disabled.

  • Selected: A Boolean property that is false by default. If set to true, the ListItem will be selected by default.

Adding List Items to List Controls

To work with List Controls, add a new Web Form to your project and name it ListControls1.aspx. Then, add one DropDownList, ListBox, RadioButtonList, and CheckBoxList control to the form.

You can add ListItems to List Controls in the following ways:

  1. Using the Items Property windows:

    • In the design view, select the DropDownList.

    • Go to its properties, select the Items property, and click the button next to it.

    • In the "ListItem Collection Editor" window, click "Add" to create a new ListItem.

    • Enter the Text and Value for each ListItem.

For example, add the following countries to the DropDownList:

    <asp:ListItem Value="C1">India</asp:ListItem>
    <asp:ListItem Value="C2">Japan</asp:ListItem>
    <asp:ListItem Value="C3">China</asp:ListItem>
    <asp:ListItem Value="C4">France</asp:ListItem>
    <asp:ListItem Value="C5">America</asp:ListItem>
    <asp:ListItem Value="C6">Australia</asp:ListItem>
  1. Manually Writing Code:

    • You can manually add ListItems in the Source View. For example, to add items to a ListBox:
    <asp:ListItem Text="Kerala" Value="S1" />
    <asp:ListItem Text="Tamil Nadu" Value="S2" />
    <asp:ListItem Text="Karnataka" Value="S3" />
    <asp:ListItem Text="Telangana" Value="S4" />
    <asp:ListItem Text="Maharashtra" Value="S5" />
    <asp:ListItem Text="Andhra Pradesh" Value="S6" />
  1. Using C# Code:

    • You can add items programmatically in the Page_Load event.

    • We can also add items to List Controls through C# code in the Code View by calling the Items.Add method on the ListControl. This method is overloaded, providing two options:

      1. <ListControl>.Items.Add(string Item)

      2. <ListControl>.Items.Add(ListItem Item)

Note: In the first method, where we pass a string as a parameter, the method internally creates a ListItem. The Text and Value properties of this ListItem will both be set to the string that was passed in. In the second method, you need to create a ListItem with separate Text and Value properties and then add it to the ListControl.

  • To test this, go to the ListControl.aspx.cs file and write the following code in the Page_Load event handler:

      RadioButtonList1.Items.Add("Delhi"); //Key is also 'Delhi'
      RadioButtonList1.Items.Add("Kolkata");
      RadioButtonList1.Items.Add("Mumbai");
      RadioButtonList1.Items.Add(new ListItem("Chennai", "City4"));
      RadioButtonList1.Items.Add(new ListItem("Bengaluru", "City5"));
      RadioButtonList1.Items.Add(new ListItem("Hyderabad", "City6"));
    
  1. Using the Items.AddRange Method:

    • Similar to the above, we have another method called "Items.AddRange". Using this method, we can add an array of ListItems to the control all at once.

        <ListControl>.Items.AddRange(ListItem[] Items)
      
    • You can add an array of ListItems at once:

    ListItem color1 = new ListItem("Red", "Color1");
    ListItem color2 = new ListItem("Blue", "Color2");
    ListItem color3 = new ListItem("White", "Color3");
    ListItem color4 = new ListItem("Green", "Color4");
    ListItem color5 = new ListItem("Purple", "Color5");
    ListItem color6 = new ListItem("Magenta", "Color6");
    ListItem[] colors = new ListItem[] { color1, color2, color3, color4, color5, color6 };
    CheckBoxList1.Items.AddRange(colors);
    //Or
    ListItem[] colors = new ListItem[]
    {
        new ListItem("Red", "Color1"),
        new ListItem("Blue", "Color2"),
        new ListItem("White", "Color3"),
        new ListItem("Green", "Color4"),
        new ListItem("Purple", "Color5"),
        new ListItem("Magenta", "Color6")
    };
    CheckBoxList1.Items.AddRange(colors);
    //Or
    CheckBoxList1.Items.AddRange(new ListItem[] {
    new ListItem("Red", "Color1"),
    new ListItem("Blue", "Color2"),
    new ListItem("White", "Color3"),
    new ListItem("Green", "Color4"),
    new ListItem("Purple", "Color5"),
    new ListItem("Magenta", "Color6")
    });
  1. Using the DataSource Property:

    • By using the "DataSource" property of List Controls, we can assign values from a data source like a file or database.

    • You can bind a List Control to a data source like a file or database:

    <ListControl>.DataSource = <Data_Table>;
    <ListControl>.DataTextField = <Column_Name>;
    <ListControl>.DataValueField = <Column_Name>;
    <ListControl>.DataBind();
    //Example:
    // Bind the data to the DropDownList
    DropDownList1.DataSource = reader;
    DropDownList1.DataTextField = "CountryName";
    DropDownList1.DataValueField = "CountryID";
    DropDownList1.DataBind();

Behavior of Each List Control

  1. DropDownList: Used for single selection.

  2. ListBox: Supports single selection by default, but can support multiple selections by setting the SelectionMode property to "Multiple".

  3. RadioButtonList: Similar to DropDownList, supports single selection only, with a radio button beside each item.

  4. CheckBoxList: Supports multi-selection, with a checkbox beside each item.

Note: RadioButtonList and CheckBoxList controls have a RepeatDirection property to specify the direction (vertical or horizontal) in which items are laid out. The RepeatLayout property allows you to set the layout to "Table", "Flow", "OrderedList", or "UnorderedList". The RepeatColumns property lets you specify the number of columns to display.

RadioButtonList and CheckBoxList have a property called “RepeatDirection” that lets you set the direction of the list items. The default is “Vertical,” but you can change it to “Horizontal.” The “RepeatLayout” property sets the layout of the list items. The default is “Table,” but you can change it to “Flow,” “OrderedList,” or “UnOrderedList.” Note that “OrderedList” and “UnOrderedList” layouts only work when “RepeatDirection” is set to “Vertical.” The “RepeatColumns” property lets you specify the number of columns for the list items.

Accessing Values from List Controls

To access values from List Controls, the following members are available:

  1. Items: Accesses all items of a List Control as a ListItem array. By using this property, we can access all the tems of a ListControl, which returns them in the form of a ListItem Aarray.

     <ListControl>.Items => ListItem[]
    
  2. SelectedItem: Accesses the selected item as a ListItem. By using this property, we can access the “SelectedItem” frorm the ListControl, which will return the value as a ListItem.

     <ListControl>.SelectedItem => ListItem (Text and Value)
    
  3. SelectedValue: Returns the value of the selected ListItem as a string.

     <ListControl>.SelectedValue => String (Only Value)
    
  4. Text: Similar to SelectedValue, returns the value of the selected ListItem as a string. Only returns the “Value” that is associated with a selected ListItem in the form of a string.

     <ListControl>.Text => String (Only Value)
    
  5. SelectedIndex: Returns the index position of the selected ListItem as an integer.

     ListControl>.SelectedIndex => int
    
  6. GetSelectedIndices(): A method available in the ListBox control that returns an array of indices corresponding to the selected items.

     <ListBox>.GetSelectedIndices() => int[]
    

Note: The first five members are available in all List Controls, while the last member, GetSelectedIndices(), is specific to the ListBox control.


XML: Extensible Markup Language:

  • XML is a markup language like HTML, but it is mainly used to describe the content of a text document.

  • It is often used to transport data between machines, along with other formats like Excel and CSV (Comma Separated Values).

  • XML can also serve as a temporary database in scenarios where access to a live database is not available.

  • XML is platform-independent, meaning it can be used on any operating system, and most applications provide options to read data from XML files.

  • Unlike HTML, where the tags are pre-defined, XML lets users create their own tags.

  • XML documents should be saved with a ".xml" extension.

  • An XML document must have exactly one root element.

  • A simple XML document looks like this:

      <Employees>
          <Employee SerialNo="1">
              <Id>1001</Id>
              <Name>Scott</Name>
              <Job>Manager</Job>
              <Salary>50000</Salary>
          </Employee>
          <Employee SerialNo="2">
              <Id>1002</Id>
              <Name>Smith</Name>
              <Job>Salesman</Job>
              <Salary>15000</Salary>
          </Employee>
          <!--Add more employee data here-->
      </Employees>
    
  • XML is case-sensitive, so the case of the opening and closing tags must match exactly:

    • <Id>101</Id> is valid.

    • <Id>101</ID> is invalid.

  • To work with XML, a software known as an XML Parser is needed, and this is built into every modern browser.

  • XML tags can also have attributes. For example, the "SerialNo" is an attribute of the "Employee" tag. Values for these attributes must be enclosed in double quotes (this is mandatory).

Note: The code in ASP.NET's ".aspx" files strictly follows XML syntax.

Loading Data into List Controls from an XML File

To load data into List Controls from an XML file, follow the steps below:

Step 1: Add a Web Form named ListControls2.aspx, and write the following code inside its <div> tag:

<table align="center" border="1">
    <caption>Product Catalog</caption>
    <tr>
        <td align="center"><asp:DropDownList ID="DropDownList1" runat="server" /></td>
        <td align="center"><asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" /></td>
        <td align="center"><asp:RadioButtonList ID="RadioButtonList1" runat="server" /></td>
        <td align="center"><asp:CheckBoxList ID="CheckBoxList1" runat="server" /></td>
    </tr>
    <tr>
        <td align="center"><asp:Button ID="Button1" runat="server" Text="Show Selected Product" /></td>
        <td align="center"><asp:Button ID="Button2" runat="server" Text="Show Selected Products" /></td>
        <td align="center"><asp:Button ID="Button3" runat="server" Text="Show Selected Product" /></td>
        <td align="center"><asp:Button ID="Button4" runat="server" Text="Show Selected Products" /></td>
    </tr>
    <tr>
        <td><asp:Label ID="Label1" runat="server" ForeColor="Red" /></td>
        <td><asp:Label ID="Label2" runat="server" ForeColor="Red" /></td>
        <td><asp:Label ID="Label3" runat="server" ForeColor="Red" /></td>
        <td><asp:Label ID="Label4" runat="server" ForeColor="Red" /></td>
    </tr>
</table>

Step 2: In the "Add New Item" window, choose the XML File item, name it Products.xml, and write the following code:

<Products>
    <Product>
        <Id>101</Id>
        <Name>Television</Name>
    </Product>
    <Product>
        <Id>102</Id>
        <Name>Microwave</Name>
    </Product>
    <Product>
        <Id>103</Id>
        <Name>Washing Machine</Name>
    </Product>
    <Product>
        <Id>104</Id>
        <Name>Refrigerator</Name>
    </Product>
    <Product>
        <Id>105</Id>
        <Name>Home Theatre</Name>
    </Product>
    <Product>
        <Id>106</Id>
        <Name>Mixer Grinder</Name>
    </Product>
    <Product>
        <Id>107</Id>
        <Name>Blu-ray Player</Name>
    </Product>
    <Product>
        <Id>108</Id>
        <Name>Split A/C</Name>
    </Product>
    <Product>
        <Id>109</Id>
        <Name>Air Cooler</Name>
    </Product>
    <Product>
        <Id>110</Id>
        <Name>Window A/C</Name>
    </Product>
</Products>

Step 3: Go to the design view of the Web Form, generate event handlers for all four buttons, and write the following code in the ListControls2.aspx.cs file:

using System.Data;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string xmlFilePath = Server.MapPath("~/Products.xml");
        DataSet ds = new DataSet();
        ds.ReadXml(xmlFilePath);

        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Id";
        DropDownList1.DataBind();
        DropDownList1.Items.Insert(0, "-Select Product-");

        ListBox1.DataSource = ds;
        ListBox1.DataTextField = "Name";
        ListBox1.DataValueField = "Id";
        ListBox1.DataBind();

        RadioButtonList1.DataSource = ds;
        RadioButtonList1.DataTextField = "Name";
        RadioButtonList1.DataValueField = "Id";
        RadioButtonList1.DataBind();

        CheckBoxList1.DataSource = ds;
        CheckBoxList1.DataTextField = "Name";
        CheckBoxList1.DataValueField = "Id";
        CheckBoxList1.DataBind();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (DropDownList1.SelectedIndex > 0)
    {
        ListItem li = DropDownList1.SelectedItem;
        Label1.Text = li.Value + ": " + li.Text;
    }
}

protected void Button2_Click(object sender, EventArgs e)
{
    Label2.Text = "";
    foreach (int index in ListBox1.GetSelectedIndices())
    {
        ListItem li = ListBox1.Items[index];
        Label2.Text += li.Value + ": " + li.Text + "<br />";
    }
}

protected void Button3_Click(object sender, EventArgs e)
{
    if (RadioButtonList1.SelectedItem != null)
    {
        ListItem li = RadioButtonList1.SelectedItem;
        Label3.Text = li.Value + ": " + li.Text;
    }
}

protected void Button4_Click(object sender, EventArgs e)
{
    Label4.Text = "";
    foreach (ListItem li in CheckBoxList1.Items)
    {
        if (li.Selected)
        {
            Label4.Text += li.Value + ": " + li.Text + "<br />";
        }
    }
}

Explanation:

  • DataSet is a class within the System.Data namespace. It can read data from an XML file or a database and hold it in a table format.

  • MapPath is a method of the HttpServerUtility class, which returns the physical path of a file when provided with the virtual path of the file.


ASP.NET Web Configuration File:

The Microsoft .NET Framework and ASP.NET use XML-formatted “.config” files to set up applications. These configuration files are text-based XML files that define various configuration options. There can be multiple ".config" files on one system. The behavior of an ASP.NET application is affected by settings in configuration files like “machine.config” and “web.config”.

  • Machine.config: System-wide configuration settings for the .NET Framework are defined in the Machine.config file. This file is located in the %SystemRoot%\Microsoft.NET\Framework\%VersionNumber%\CONFIG\ folder. The default settings in the Machine.config file can be modified to affect the behavior of all .NET applications on the system.

  • Web.config: You can change the ASP.NET configuration settings for a single application by creating a Web.config file in the root folder of the application. The settings in the Web.config file override the settings in the Machine.config file. The Web.config file must contain only entries for configuration items that override the settings in the Machine.config file. At a minimum, the Web.config file must have the <configuration> element and the <system.web> element. These elements will contain individual configuration elements as shown below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
    </system.web>
</configuration>

The first line of the Web.config file describes the document as XML-formatted and specifies the character encoding type. This first line must be the same for all .config files. The lines that follow mark the beginning and the end of the <configuration> and <system.web> elements of the Web.config file. By themselves, these lines do nothing, but they provide a structure that allows you to add future configuration settings. Most ASP.NET configuration settings are added between the <system.web> and </system.web> lines.

Benefits of the ASP.NET Configuration System:

The ASP.NET configuration system provides the following benefits:

  • XML-based Configuration: Configuration information is stored in XML-based text files. You can use any standard text editor or XML parser to create and edit ASP.NET configuration files.

  • Hierarchical Configuration: Multiple configuration files, all named Web.config, can appear in multiple directories on an ASP.NET web application server. Each Web.config file applies configuration settings to its own directory and all child directories below it. Configuration files in child directories can supply additional configuration information or override settings inherited from parent directories. The root configuration file named Machine.config provides ASP.NET configuration settings for the entire web server.

  • Runtime Configuration Calculation: At runtime, ASP.NET uses the configuration information provided by the Web.config files in a hierarchical virtual directory structure to compute a collection of configuration settings for each unique URL resource. The resulting configuration settings are then cached for all subsequent requests to that resource. Note that inheritance is defined by the incoming request path (the URL), not by the physical paths to the resources on disk.

  • Automatic Configuration Updates: ASP.NET detects changes to configuration files and automatically applies new configuration settings to web resources affected by the changes. The server does not need to be rebooted for changes to take effect. Hierarchical configuration settings are automatically recalculated and recached whenever a configuration file in the hierarchy is changed.

  • Extensibility: The ASP.NET configuration system is extensible. You can define new configuration parameters and write configuration section handlers to process them.

  • Security: ASP.NET helps protect configuration files from outside access by configuring Internet Information Services (IIS) to prevent direct browser access to configuration files. An HTTP 403 (forbidden) error is returned to any browser attempting to request a configuration file directly.

Key Sections in the Web.config File

  • <system.web>: This element contains information about how the ASP.NET hosting layer manages application behavior.

  • <system.codedom>: This element contains compiler configuration settings for language providers installed on a computer, in addition to the default providers installed with the .NET Framework, such as the CSharpCodeProvider and the VBCodeProvider.

  • <system.net>: This element contains settings that specify how the .NET Framework connects to the network, i.e., it contains network connection details.

  • <appSettings>: This element stores custom application configuration information, such as file paths, XML web service URLs, or any other custom configuration information for an application. Information is stored in the <appSettings> as key/value pairs and is accessed in code using the ConfigurationSettings class.

  • <connectionStrings>: This element contains initialization information passed as a parameter from an application to a data source. Information is stored in the <connectionStrings> as key/value pairs and is accessed in code using the ConfigurationSettings class.

Validation Controls

Validation is an important part of any web application. Whenever a user provides input on a web page, it must always be validated before being processed by various layers of an application. Without validation, there is a risk that the data might be incorrect. Therefore, it is crucial to validate user input. In web applications, validations are performed at two different levels:

  1. Client-Side Validation

  2. Server-Side Validation

Client-Side Validation

Client-side validation happens in the user's browser, usually with JavaScript. Developers have used this method for many years because it gives users quick feedback. The main benefit is that it stops the page from being sent to the server until the client-side validation is successful. However, it relies on the browser and scripting language support.

Server-Side Validation

Server-side validation happens on the server. It is more secure. The main benefit is that even if a user skips client-side validation by turning off JavaScript, the server can still catch the issue. Server-side validation makes sure no bad data is processed by the application. Developers often prefer it because it does not depend on the browser or scripting languages, making it more reliable.

Validation Controls in ASP.NET

ASP.NET provides validation controls that make it easy to check user input. These controls do both client-side and server-side validation. First, they use JavaScript for client-side validation to stop the page from being submitted if there are errors. If JavaScript is turned off, the page is still sent to the server, where the controls check the data again. This ensures server-side validation always happens, adding an extra layer of security.

A key part of making ASP.NET web pages is checking that user input is correct. ASP.NET has validation controls to find errors and show messages to users if needed. Here are the validation controls available in ASP.NET:

  • RequiredFieldValidator

  • CompareValidator

  • RangeValidator

  • RegularExpressionValidator

  • CustomValidator

  • ValidationSummary

Common Properties and Methods of Validation Controls

Validation controls in ASP.NET inherit from the BaseValidator class, which provides common properties, events, and methods. Here are some key properties:

  1. ControlToValidate: This property specifies the ID of the input control that must be validated by the validation control.

  2. Display: This enumerated property sets how the error message is shown on the browser. It can be set to Static, Dynamic, or None.

  3. EnableClientScript: This Boolean property indicates whether client-side validation should take place. The default value is true. If set to false, client-side validation will not occur.

  4. Enabled: This Boolean property, with a default value of true, enables or disables the validator. When set to false, the validator does not validate the input control.

  5. ErrorMessage: This property specifies the error message that is displayed when validation fails. This message is also used by the ValidationSummary control.

  6. Text: Text: This is similar to the "ErrorMessage" property, but if both properties are set, "Text" is given priority and is shown where the validation control is placed. The "ErrorMessage" value is used by the "ValidationSummary" control.

  7. SetFocusOnError: This Boolean property, with a default value of false, sets the focus back to the input control that failed validation if the validation fails.

  8. ValidationGroup: This property groups a set of controls on the page so that validations in one group do not affect validations in another group when the page is submitted.

  9. IsValid: This Boolean property indicates whether the value of the input control is valid.

  10. ForeColor: This property specifies the color in which error messages are displayed.

Unobtrusive Validation Mode:

ASP.NET Web Forms have provided validation controls since the initial releases. Prior to ASP.NET 4.5, when using a validator to validate any control and employing client-side validation, JavaScript was generated and rendered as HTML. Additionally, supportive JavaScript files were loaded by the browser for validation.

Unobtrusive JavaScript is a way of writing JavaScript that separates document content from script content, allowing for a clear distinction between them. This approach makes code less error-prone, easier to update, and easier to debug.

From ASP.NET 4.5, we need to specify how ASP.NET enables the built-in validator controls to use Unobtrusive JavaScript for client-side validation. We can set it to either “None” or “Web Forms”. If the value is “None”, the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation. If the value is “Web Forms”, ASP.NET uses HTML 5 data-attributes and JavaScript from an added script reference for client-side validation. We can set the unobtrusive validation mode in the Global.asax file, individual Web Forms, or Web.Config.

Option 1: Set Unobtrusive Validation Mode in Global.asax

To set Unobtrusive Validation Mode in the Global.asax file, we need to set the UnobtrusiveValidationMode property of the ValidationSettings class in the Application_Start Event Handler by importing the namespace System.Web.UI as follows:

ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;

This should be placed in the Application_Start event handler by importing the System.Web.UI namespace.

Option 2: Set Unobtrusive Validation Mode in a Web Form

To set Unobtrusive Validation Mode in a Web Form, we need to set the UnobtrusiveValidationMode property of the ValidationSettings class in the Page_Load event handler of each Web Form as follows:

this.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;

This should be placed in the Page_Load event handler of each web form.

Option 3: Set Unobtrusive Validation Mode in Web.config

To set unobtrusive validation mode in the Web.config file, add a new key under the tag with the name “ValidationSettings:UnobtrusiveValidationMode” and value “none” as shown below. If the tag is already there, just add the following:

<add key="ValidationSettings:UnobtrusiveValidationMode" value="none" />

If the <appSettings> tag is not present, include it as follows:

<appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="none" />
</appSettings>

RequiredFieldValidator

This validation control checks if an input field is empty, making sure a value is entered or selected. It has a specific property:

  1. InitialValue: This property sets a value that the validation control ignores when checking the input field.

To demonstrate how to use the RequiredFieldValidator, add a WebForm to your project and name it Validations1.aspx. Then, write the following code within the <div> tag:

Enter Name: 
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator 
    ID="rfvName" 
    runat="server" 
    ControlToValidate="txtName" 
    ForeColor="Red"
    ErrorMessage="Can't leave the field empty." 
    Display="Dynamic" 
    SetFocusOnError="true" />
<br />

Select Country:
<asp:DropDownList ID="ddlCountries" runat="server">
    <asp:ListItem Text="-Select Country-" Value="NS" />
    <asp:ListItem Text="India" Value="Country1" />
    <asp:ListItem Text="Japan" Value="Country2" />
    <asp:ListItem Text="China" Value="Country3" />
    <asp:ListItem Text="England" Value="Country4" />
    <asp:ListItem Text="America" Value="Country5" />
    <asp:ListItem Text="Australia" Value="Country6" />
</asp:DropDownList>
<asp:RequiredFieldValidator 
    ID="rfvCountry" 
    runat="server" 
    ControlToValidate="ddlCountries" 
    ForeColor="Red"
    ErrorMessage="Please select a country." 
    InitialValue="NS" 
    Display="Dynamic" 
    SetFocusOnError="true" />
<br />

<asp:Button ID="btnSubmit" runat="server" Text="Submit Data" />
<br />
<asp:Label ID="lblMsg" runat="server" />

Next, go to the “aspx.cs” file and write the following code:

Code under Page_Load Event Handler:

if (!IsPostBack) {
    txtName.Focus();
}

Code under the Submit Button Click Event Handler:

lblMsg.Text = $"Hello {txtName.Text}, the country you belong to is: {ddlCountries.SelectedItem.Text}";

Now run the WebForm and observe the output. When the two input controls are not filled with values and the Submit button is clicked, the page will not be submitted to the server. However, when values are provided and the Submit button is clicked, the page will be submitted to the server, and a message will be displayed under the Label control.

Handling JavaScript Disabled Scenarios

When implementing data validation logic using JavaScript, one issue you might encounter is that if the client disables JavaScript in their browser (Browser URL enter chrome://settings/content/javascript then disable the javascript), the page will be submitted to the server even if the validations fail. The logic on the server will execute regardless of whether it depends on the validations.

To test this, disable JavaScript in your browser and test the page again. Even if the input controls are not filled, clicking the Submit button will submit the page to the server, displaying the previous message in the Label control.

The advantage of using ASP.NET Validation Controls is that even if JavaScript is disabled and the page is submitted to the server, the validation controls will re-validate the input controls on the server. They will set the validation control’s IsValid property to a Boolean value: true if the validation is successful and false if it fails.

To implement server-side logic based on validation, use the following condition:

if (rfvName.IsValid && rfvCountry.IsValid) {
    lblMsg.ForeColor = System.Drawing.Color.Green;
    lblMsg.Text = $"Hello user, the name you entered is: {txtName.Text} and your selected country is: {ddlCountries.SelectedItem.Text}";
} else {
    lblMsg.ForeColor = System.Drawing.Color.Red;
    lblMsg.Text = "Data validations failed.";
}

Simplifying Validation Check

The problem with the above code is that when there are multiple validation controls, checking each control's IsValid value can become complicated. You can avoid this by using the Page class’s IsValid property. Each validation control first performs data validation, sets its IsValid property to true or false based on the success or failure of the validation, and finally, the Page class’s IsValid property is set to true if all validation controls have IsValid set to true. If any validation control’s IsValid property is false, the Page class’s IsValid property will also be false.

You can simplify the condition in the previous code as follows:

if (IsValid) {
    lblMsg.ForeColor = System.Drawing.Color.Green;
    lblMsg.Text = $"Hello user, the name you entered is: {txtName.Text} and your selected country is: {ddlCountries.SelectedItem.Text}";
} else {
    lblMsg.ForeColor = System.Drawing.Color.Red;
    lblMsg.Text = "Data validations failed.";
}

Performing Validation on Control Focus Leave

Currently, validations are performed when the Submit button is clicked. If you want the validations to be performed when the focus leaves the control, add the following code to the Page_Load event handler:

txtName.Attributes.Add("onblur", "ValidatorValidate(rfvName)");
ddlCountries.Attributes.Add("onblur", "ValidatorValidate(rfvCountry)");

These statements bind the validation control's JavaScript function to the controls' onblur event, so the event will fire when the focus leaves the controls.

RangeValidator:

This validation control is used to check whether the value entered into an input control is within a specified range. It has the following properties:

  1. MinimumValue: Specifies the lowest value that can be entered into the input control being validated.

  2. MaximumValue: Specifies the highest value that can be entered into the input control being validated.

  3. Type: Specifies the data type for the values being compared. The possible values are: String, Integer, Double, Date, and Currency. The default value is String.

Note: Except for the RequiredFieldValidator, none of the other validation controls can check for empty values. Therefore, when using other validation controls, you must also use a RequiredFieldValidator if you want to check for empty values. Each validation control can be associated with only one input control, but one input control can be associated with multiple validation controls.

To demonstrate this, add a new WebForm to your project and name it Validations2.aspx. Then, design the form as follows:

Design Instructions:

Place the following code inside the <div> tag of the "Validations2.aspx" file:

<table align="center">
    <caption>Journey Planner</caption>
    <tr>
        <td>Enter Name:</td>
        <td><asp:TextBox ID="txtName" runat="server" /></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" /></td>
    </tr>
    <tr>
        <td>Enter Age:</td>
        <td><asp:TextBox ID="txtAge" runat="server" /></td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" /><br />
            <asp:RangeValidator ID="RangeValidator1" runat="server" />
        </td>
    </tr>
    <tr>
        <td>Date of Journey:</td>
        <td>
            <asp:TextBox ID="txtDate" runat="server" />
            <asp:ImageButton ID="imgDate" runat="server" ImageUrl="~/Images/Calendar.ico" Width="20" Height="20" ImageAlign="AbsMiddle" />
            <asp:Calendar ID="cldDate" runat="server" Visible="false" />
        </td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" /><br />
            <asp:RangeValidator ID="RangeValidator2" runat="server" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center"><asp:Button ID="btnConfirm" runat="server" Text="Confirm Booking" /></td>
        <td></td>
    </tr>
    <tr>
        <td colspan="3"><asp:Label ID="lblMsg" runat="server" /></td>
    </tr>
</table>

Next Steps:

  1. In Design View, select all five validation controls at once, press "F4" to open the Properties window, and set the following properties:

    • Display: Dynamic

    • ForeColor: Red

    • SetFocusOnError: True

  2. Set the properties of each validation control as follows:

    • RequiredFieldValidator1:

      • ID: rfvName

      • ControlToValidate: txtName

      • ErrorMessage: Name field can't be left empty.

    • RequiredFieldValidator2:

      • ID: rfvAge

      • ControlToValidate: txtAge

      • ErrorMessage: Age field can't be left empty.

    • RequiredFieldValidator3:

      • ID: rfvDate

      • ControlToValidate: txtDate

      • ErrorMessage: Journey date can't be left empty.

    • RangeValidator1:

      • ID: rvAge

      • ControlToValidate: txtAge

      • MinimumValue: 18

      • MaximumValue: 65

      • ErrorMessage: Traveler’s age should be between 18 - 65 years.

      • Type: Integer

    • RangeValidator2:

      • ID: rvDate

      • ControlToValidate: txtDate

      • Type: Date

      • ErrorMessage: Travel date should be within 90 days from the current date.

Code for "Validations2.aspx.cs" File:

Add the following code in the "Validations2.aspx.cs" file:

Code under Page_Load:

rvDate.MinimumValue = DateTime.Now.ToShortDateString();
rvDate.MaximumValue = DateTime.Now.AddDays(90).ToShortDateString();

if (!IsPostBack) {
    txtName.Focus();
}

Code under Image Button Click Event:

if (cldDate.Visible) {
    cldDate.Visible = false;
} else {
    cldDate.Visible = true;
}
//Or
cldDate.Visible = !cldDate.Visible;

Code under Calendar Selection Changed Event:

txtDate.Text = cldDate.SelectedDate.ToShortDateString();
cldDate.Visible = false;

Code under Confirm Button Click Event:

if (IsValid) {
    lblMsg.ForeColor = System.Drawing.Color.Green;
    lblMsg.Text = "Your booking is confirmed.";
} else {
    lblMsg.ForeColor = System.Drawing.Color.Red;
    lblMsg.Text = "Validations failed, please re-check your data.";
}

Important Note: When running the WebForm, you might face an issue where clicking the ImageButton to open the calendar requires a postback, but the validation controls won't allow it unless all validations pass. To fix this, set the ValidationGroup property of the ImageButton to a value like "DateGroup". This way, when the ImageButton is clicked, only the controls in this group are validated. Since there are no other controls in this group right now, the postback will happen without problems.

CompareValidator

This control is used for performing three types of validations:

  1. Compare the value of an input control with another input control.

  2. Compare the value of an input control with a fixed value.

  3. Data type check.

Properties specific to CompareValidator:

  1. ControlToCompare: Specifies the ID of another input control to compare with the input control being validated.

  2. ValueToCompare: A fixed value to compare with the current input.

  3. Operator: Specifies the type of comparison to be performed. The possible values are:

    • Equal [default]

    • NotEqual

    • GreaterThan

    • GreaterThanEqual

    • LessThan

    • LessThanEqual

    • DataTypeCheck

  4. Type: Specifies the data type of the values being compared. Possible values include:

    • String [default]

    • Integer

    • Double

    • Date

    • Currency

Instructions to Add a New WebForm:

Add a new WebForm to your project and name it Validations3.aspx. Then, design the form as follows:

Design Instructions:

Place the following code inside the <div> tag of the Validations3.aspx file:

<table align="center">
    <caption>Registration Form</caption>
    <tr>
        <td>Enter Name:</td>
        <td><asp:TextBox ID="txtName" runat="server" /></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" /></td>
    </tr>
    <tr>
        <td>Enter Password:</td>
        <td><asp:TextBox ID="txtPwd" runat="server" TextMode="Password" /></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" /></td>
    </tr>
    <tr>
        <td>Confirm Password:</td>
        <td><asp:TextBox ID="txtCPwd" runat="server" TextMode="Password" /></td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" /><br />
            <asp:CompareValidator ID="CompareValidator1" runat="server" />
        </td>
    </tr>
    <tr>
        <td>Date of Birth:</td>
        <td>
            <asp:TextBox ID="txtDate" runat="server" />
            <asp:ImageButton ID="imgDate" runat="server" ImageUrl="~/Images/Calendar.ico" Width="20" Height="20" ImageAlign="AbsMiddle" ValidationGroup="DateGroup" />
            <asp:Calendar ID="cldDate" runat="server" Visible="false" />
        </td>
        <td>
            <asp:CompareValidator ID="CompareValidator2" runat="server" /><br />
            <asp:CompareValidator ID="CompareValidator3" runat="server" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button ID="btnRegister" runat="server" Text="Register" />
        </td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td colspan="3"><asp:Label ID="lblMsg" runat="server" /></td>
    </tr>
</table>

Next Steps:

  1. In Design View, select all six validation controls at once, press "F4" to open the Properties window, and set the following properties:

    • Display: Dynamic

    • ForeColor: Red

    • SetFocusOnError: True

  2. Set the properties of each validation control as follows:

    • RequiredFieldValidator1:

      • ID: rfvName

      • ControlToValidate: txtName

      • ErrorMessage: Name field can't be left empty.

    • RequiredFieldValidator2:

      • ID: rfvPwd

      • ControlToValidate: txtPwd

      • ErrorMessage: Password field can't be left empty.

    • RequiredFieldValidator3:

      • ID: rfvCPwd

      • ControlToValidate: txtCPwd

      • ErrorMessage: Confirm password field can't be left empty.

    • CompareValidator1:

      • ID: cvCPwd

      • ControlToValidate: txtCPwd

      • ControlToCompare: txtPwd

      • Type: String

      • Operator: Equal

      • ErrorMessage: Confirm password should match with password.

    • CompareValidator2:

      • ID: cvDate1

      • ControlToValidate: txtDate

      • Operator: DataTypeCheck

      • ErrorMessage: Entered value is not in a valid date format.

      • Type: Date

    • CompareValidator3:

      • ID: cvDate2

      • ControlToValidate: txtDate

      • Operator: LessThanEqual

      • ErrorMessage: You need to attain 18 years of age for registration.

      • Type: Date

Code for "Validations3.aspx.cs" File:

Add the following code in the "Validations3.aspx.cs" file:

Code under Page_Load:

if (!IsPostBack) {
    txtName.Focus();
}
cvDate2.ValueToCompare = DateTime.Now.AddYears(-18).ToShortDateString();

Code under Image Button Click Event:

if (cldDate.Visible) {
    cldDate.Visible = false;
} else {
    cldDate.Visible = true;
}

Code under Calendar Selection Changed Event:

txtDate.Text = cldDate.SelectedDate.ToShortDateString();
cldDate.Visible = false;

Code under Register Button Click Event:

if (IsValid) {
    lblMsg.ForeColor = System.Drawing.Color.Green;
    lblMsg.Text = "Your registration is successful.";
} else {
    lblMsg.ForeColor = System.Drawing.Color.Red;
    lblMsg.Text = "Validations failed, please re-check your data.";
}

RegularExpressionValidator

  • This control validates input by using special characters known as Regular Expressions or Regex. These are special characters that allow us to perform data validations without writing complex logic.

Understanding Regular Expressions:

  • B => Braces:

    • []: Used to specify the characters that are allowed.

      • Example: [a-m], [A-K], [0-6], [A-Za-z0-9]
    • {}: Used to specify the number of characters that are allowed.

      • Example: {1}, {4,7}, {4,}
    • (): Used to specify a list of options that are accepted.

      • Example: (com|net|in|edu)
  • C => Caret (^):

    • Represents the start of an expression.
  • D => Dollar ($):

    • Represents the end of an expression.

Examples:

  • [A-K]: Accepts 1 alphabet between A to K.

  • [a-m]{5}: Accepts 5 lowercase alphabets between a to m.

  • [a-z]{3}[0-9]{5}: Accepts 3 lowercase alphabets followed by 5 numeric digits.

Note: In the above examples, after the validating expression, anything can be accepted. To overcome this, you need to make the expressions rigid by using ^ at the start and $ at the end of the expression:

  • ^[a-z]{3}[0-9]{5}$: Accepts only 8 characters, 3 lowercase alphabets followed by 5 numeric digits.

Special Characters in Regular Expressions:

  • \s: Accepts whitespace.

  • \S: Does not accept whitespace.

  • \d: Accepts only numeric values.

  • \D: Accepts only non-numeric values.

  • \w: Accepts only alphanumeric values.

  • \W: Accepts only non-alphanumeric values.

Validation Expressions Using Regular Expressions:

  • \d{6}: Indian Postal Code

  • \d{3}-\d{7}: Indian Railway PNR

  • \d{4} \d{4} \d{4}: Aadhaar Number

  • \d{4} \d{4} \d{4} \d{4}: Credit Card Number

  • http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?: Website URL Validation

  • \w+[\w-\.]*@\w+((-\w+)|(\w*))\.[a-z]{2,3}: Email Validation

  • [6-9]\d{9}: Mobile number validation that checks if the number starts with 6, 7, 8, or 9 and is exactly 10 digits long.

  • [0][6-9]\d{9}: Mobile number validation that checks if the number starts with 0, followed by 6, 7, 8, or 9, and is exactly 11 digits long.

  • ^[0][6-9]\d{9}$|^[6-9]\d{9}$: Mobile number validation which checks if the number starts with 0, it should be 11 digits long; otherwise, it should be 10 digits long.

  • ^\d{6,8}$|^[6-9]\d{9}$: Validation for either a 6-8 digit landline number or a 10-digit mobile number that starts with 6, 7, 8, or 9.

Note: You can use Regular Expressions in ASP.NET by using the RegularExpressionValidator control and specify the regular expression under its ValidationExpression property.

Properties Specific to RegularExpressionValidator:

  1. ValidationExpression: Use this property to specify the validation expression for the control. You can either choose from a list of pre-defined expressions by clicking on the button next to the property (which will launch the "Regular Expression Editor" and display a list of pre-defined expressions for Email ID Validation, Website URL Validation, etc.) or enter a custom validation expression.

Add a New WebForm:

Add a new WebForm to your project and name it "Validations4.aspx". Design the form as follows:

<table align="center">
    <caption>Company Registration Form</caption>
    <tr>
        <td>Company Name:</td>
        <td><asp:TextBox ID="txtName" runat="server" /></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" /></td>
    </tr>
    <tr>
        <td>Contact No:</td>
        <td><asp:TextBox ID="txtPhone" runat="server" /></td>
        <td><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" /></td>
    </tr>
    <tr>
        <td>Email Id:</td>
        <td><asp:TextBox ID="txtEmail" runat="server" /></td>
        <td><asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" /></td>
    </tr>
    <tr>
        <td>Website Url:</td>
        <td><asp:TextBox ID="txtUrl" runat="server" /></td>
        <td><asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center"><asp:Button ID="btnRegister" runat="server" Text="Register" /></td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td colspan="3"><asp:Label ID="lblMsg" runat="server" /></td>
    </tr>
</table>

Next Steps:

  1. Select all four validation controls at once, press "F4" to open the Properties window, and set the following properties:

    • Display: Dynamic

    • ForeColor: Red

    • SetFocusOnError: True

  2. Set the properties of each validation control as follows:

    • RequiredFieldValidator1:

      • ID: rfvName

      • ControlToValidate: txtName

      • ErrorMessage: Company name field can't be left empty.

    • RegularExpressionValidator1:

      • ID: revPhone

      • ControlToValidate: txtPhone

      • ValidationExpression: ^\d{6,8}$|^[6-9]\d{9}$

      • ErrorMessage: Contact no. can either be Landline (6-8 digits) or Mobile (10 digits).

    • RegularExpressionValidator2:

      • ID: revEmail

      • ControlToValidate: txtEmail

      • ErrorMessage: Given input is in an invalid Email ID format.

      • ValidationExpression: Click on the button next to it and select "Internet e-mail address" in the Regular Expression Editor.

    • RegularExpressionValidator3:

      • ID: revUrl

      • ControlToValidate: txtUrl

      • ErrorMessage: Given input is in an invalid Website URL format.

      • ValidationExpression: Click on the button next to it and select "Internet URL" in the Regular Expression Editor.

Code for "Validations4.aspx.cs" File:

Add the following code in the "Validations4.aspx.cs" file:

Code under Page_Load:

if (!IsPostBack) {
    txtName.Focus();
}

Code under Register Button Click Event:

if (IsValid) {
    lblMsg.ForeColor = System.Drawing.Color.Green;
    lblMsg.Text = "Your company registration is successful.";
} else {
    lblMsg.ForeColor = System.Drawing.Color.Red;
    lblMsg.Text = "Your company registration failed due to validation errors.";
}

CustomValidator

This control doesn't have any built-in logic for data validation. We need to write all the logic ourselves, similar to writing manual JavaScript code. The advantage is that we can use JavaScript for client-side validation and also use C# code for server-side validation. This way, even if JavaScript is disabled in the client's browser, the data will still be validated on the server.

Note: We don't need to set the "ControlToValidate" property for CustomValidator, so this Validator can validate more than one input control.

Important Properties:

  1. ClientValidationFunction: Specifies the name of the JavaScript function that handles client-side validation.

  2. ServerValidate: An event where the server-side validation logic is implemented.

Implementing CustomValidator in ASP.NET

Step 1: Create a New Web Form

Create a new Web Form named Validations5.aspx and design it as follows:

<table align="center">
    <caption>Feedback Form</caption>
    <tr>
        <td>Name:</td>
        <td><asp:TextBox ID="txtName" runat="server" /></td>
        <td><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" /></td>
    </tr>
    <tr>
        <td>Phone No:</td>
        <td><asp:TextBox ID="txtPhone" runat="server" /></td>
        <td rowspan="2">
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" /><br />
            <asp:CustomValidator ID="CustomValidator1" runat="server" /><br />
            <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" />
        </td>
    </tr>
    <tr>
        <td>Email Id:</td>
        <td><asp:TextBox ID="txtEmail" runat="server" /></td>
    </tr>
    <tr>
        <td>Comments:</td>
        <td><asp:TextBox ID="txtComments" runat="server" Rows="3" TextMode="MultiLine" /></td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" /><br />
            <asp:CustomValidator ID="CustomValidator2" runat="server" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center"><asp:Button ID="btnSubmit" runat="server" Text="Submit" /></td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td colspan="3"><asp:Label ID="lblMsg" runat="server" /></td>
    </tr>
</table>

Step 2: Set Validation Control Properties

Select all six validation controls, press F4, and set the following properties in the property window:

  • Display: Dynamic

  • ForeColor: Red

  • SetFocusOnError: True

Next, configure individual properties for each validation control:

  1. RequiredFieldValidator1:

    • Id: rfvName

    • ControlToValidate: txtName

    • ErrorMessage: Name field can't be left empty.

  2. RequiredFieldValidator2:

    • Id: rfvComments

    • ControlToValidate: txtComments

    • ErrorMessage: Comments field can't be left empty.

  3. RegularExpressionValidator1:

    • Id: revPhone

    • ControlToValidate: txtPhone

    • ValidationExpression: ^\d{8}$|^[6-9]\d{9}$

    • ErrorMessage: Phone no. can either be landline (8 digits) or mobile (10 digits).

  4. RegularExpressionValidator2:

    • Id: revEmail

    • ControlToValidate: txtEmail

    • ErrorMessage: Given input is an invalid Email Id format.

    • ValidationExpression: Select "Internet e-mail Address" in the Regular Expression Editor.

  5. CustomValidator1:

    • Id: cvPhoneOrEmail

    • ErrorMessage: Either Phone No. or Email Id must be provided.

    • ClientValidationFunction: PhoneOrEmail

  6. CustomValidator2:

    • Id: cvComments

    • ControlToValidate: txtComments

    • ClientValidationFunction: Check50Chars

    • ErrorMessage: Comments should be minimum 50 chars in length.

Step 3: Implement Client-Side Validation

In the Source View, add the following JavaScript code inside the <head> section:

<script>
function PhoneOrEmail(source, args) {
    if (txtPhone.value.trim().length === 0 && txtEmail.value.trim().length === 0) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}

function Check50Chars(source, args) {
    if (args.Value.trim().length < 50) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}
</script>

Step 4: Implement Server-Side Validation

In the Validations5.aspx.cs file, implement the following server-side logic:

protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        txtName.Focus();
    }
}

protected void cvPhoneOrEmail_ServerValidate(object source, ServerValidateEventArgs args) {
    if (string.IsNullOrWhiteSpace(txtPhone.Text) && string.IsNullOrWhiteSpace(txtEmail.Text)) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}

protected void cvComments_ServerValidate(object source, ServerValidateEventArgs args) {
    if (args.Value.Trim().Length < 50) {
        args.IsValid = false;
    } else {
        args.IsValid = true;
    }
}

protected void btnSubmit_Click(object sender, EventArgs e) {
    if (IsValid) {
        lblMsg.ForeColor = System.Drawing.Color.Green;
        lblMsg.Text = "Your feedback is received, we will contact you as soon as possible.";
    } else {
        lblMsg.ForeColor = System.Drawing.Color.Red;
        lblMsg.Text = "Your feedback contains errors and has not been submitted.";
    }
}

ValidationSummary

This control doesn't perform any data validations but is used only for showing error messages. Instead of displaying error messages next to the input controls, we can show all the error messages in one place, either at the top or bottom of the page. When we add this control to a page, it will automatically display the error messages from all the validation controls on that page. To test the ValidationSummary control on our current page, "Validations5.aspx," go to design view, drag and drop the ValidationSummary control just below the table, and set the ForeColor property to "Red."

Now run the Web Form and observe the output. If any validations fail, all the error messages will be shown by the ValidationSummary control where we placed it. This control will gather all the error messages from the 6 validation controls on the page. However, we also see error messages next to the input controls. To avoid this, set the Text property of the validation controls so that a text value is displayed next to the input controls, and the error messages are shown by the ValidationSummary control. To test this, go to the properties of all 6 validation controls on the page and set the Text value to "*". Now run the form and notice the difference: "*" will appear next to the input control where the validation failed, and all the error messages will be displayed by the ValidationSummary control.

Properties Specific to ValidationSummary Control

  1. ShowSummary:

    • Type: Boolean

    • Default: true

    • Description: If set to false, the error messages will not be displayed on the screen.

  2. ShowMessageBox:

    • Type: Boolean

    • Default: false

    • Description: If set to true, the error messages will be displayed in a MessageBox.

  3. ShowValidationErrors:

    • Type: Boolean

    • Default: true

    • Description: If set to false, error messages will not be displayed either on the screen or in a MessageBox.

  4. DisplayMode:

    • Description: Specifies the format in which error messages are displayed. The available options are:

      • BulletedList: Displays errors as a bulleted list.

      • List: Displays errors as a simple list.

      • SingleParagraph: Displays all errors in a single paragraph.

Master Pages

A well-designed website usually has a consistent layout across all pages. For example, on the www.codecomponents.com website, every page has the same content at the top and bottom. The top of each page has a light gray bar with branch locations, followed by the company logo and main sections like Home, All Courses, Software Training, Services, and more. The bottom of the page includes information about clients, addresses, contact details, and quick links.

A well-designed site should make it easy to change its appearance. For example, if you need to update the look of the site—maybe by adding more menu items or using new colors, fonts, and layouts—these changes should be easy to apply across the whole site. Ideally, you shouldn't have to change each of the thousands of web pages one by one.

Introduction to Master Pages in ASP.NET:

Creating a consistent layout across your site in ASP.NET is easy with Master Pages. A Master Page is a special type of ASP.NET page that sets the layout and design for all linked Content Pages. When you change the layout or style of a Master Page, all linked Content Pages update automatically. This makes it quick and easy to change the look of your entire site.

How Master Pages Work:

When building a website with a consistent layout, each web page needs to include common formatting markup. For example, while each page on www.codecomponents.com has its unique content, each page also includes a series of common <div> elements that show the top-level section links like Home, All Courses, Software Training, Services, and so on.

There are different ways to create web pages with a consistent look. A simple but flawed method is to copy and paste the common layout markup into all web pages. However, this method has several drawbacks:

  • Error-Prone: Each time a new page is created, there's a risk of copying only a subset of the shared markup.

  • Maintenance Challenges: Any change in the shared content requires updating every single page manually.

To solve these problems, ASP.NET 2.0 and Visual Studio 2005 introduced Master Pages. A Master Page sets the overall layout for the site and defines areas where linked Content Pages can add their own content. These areas are defined using ContentPlaceHolder controls.

The Role of ContentPlaceHolder Controls:

The ContentPlaceHolder control marks a spot in the Master Page where custom content from a Content Page will go. The Master Page gives the common layout—the top, bottom, and side sections of each page—while the ContentPlaceHolder control lets individual pages add their unique content in these specific areas.

Example Layout of a Master Page

A Master Page might include a header, a footer, and a sidebar, with a ContentPlaceHolder in the middle-left for the unique content of each web page. The content within the ContentPlaceHolder changes from page to page, while the rest of the layout stays the same.

Once a master page is set up, it can be linked to a new ASP.NET page. These ASP.NET pages, called content pages, include a Content control for each ContentPlaceHolder in the master page. When someone visits the content page in a browser, the ASP.NET engine builds the master page's controls and inserts the content page's controls into the right spots. The combined controls are then turned into HTML and sent to the user's browser. The figure below shows how this works:

Creating a Master Page in ASP.NET

To create a consistent site-wide layout in ASP.NET, we use Master Pages. Follow these steps to add a Master Page to your site:

  1. Adding a Master Page:

    • Open the "Add New Item" window.

    • Select the "WebForms Master Page" option.

    • Name it "Site.master" (the .master extension is specific to Master Pages).

The first line in the Master Page's markup will be:

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="ControlsDemo.Site" %>

This is the @Master directive, similar to the @Page directive in regular ASP.NET pages, with attributes like Language, AutoEventWireup, and CodeBehind.

  1. Initial Code Structure: The initial code in the Master Page will look like this:

     <!DOCTYPE html>
     <html>
     <head runat="server">
         <title></title>
         <asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
     </head>
     <body>
         <form id="form1" runat="server">
             <div>
                 <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"></asp:ContentPlaceHolder>
             </div>
         </form>
     </body>
     </html>
    
  2. Understanding the ContentPlaceHolder Controls:

    • The ContentPlaceHolder control named head is located within the <head> section. It allows you to add content, such as styles or scripts, to the <head> element in your Content Pages.

    • The ContentPlaceHolder control named ContentPlaceHolder1 is located within the <form> tag. This serves as a placeholder for the user interface content defined in the Content Pages.

  3. Modifying the Master Page:

    • Delete the code inside the <form> tag, including the ContentPlaceHolder.

    • Replace it with the following code:

    <div id="divHeader" style="background-color: lightpink; color: aqua; text-align: center; font-size: xx-large">
        Naresh I Technologies
    </div>
    <div id="divMenu" style="background-color: beige; text-align: center">
        <asp:HyperLink ID="hlHome" runat="server" NavigateUrl="~/Home.aspx" Text="Home" />&nbsp;
        <asp:HyperLink ID="hlMission" runat="server" NavigateUrl="~/Mission.aspx" Text="Mission" />&nbsp;
        <asp:HyperLink ID="hlAbout" runat="server" NavigateUrl="~/About.aspx" Text="About" />
    </div>
    <div id="divContent">
        <asp:ContentPlaceHolder ID="body" runat="server" />
    </div>
    <div id="divFooter" style="background-color: azure">
        <fieldset style="border: dotted blue; color: brown">
            <legend>Contact Us</legend>
            Address: Opp. Satyam Theatre, Ameerpet, Hyderabad – 16 <br />
            Phone: 2374 6666 <br />
            Email: info@nareshit.com <br />
            Website: www.nareshit.com
        </fieldset>
    </div>

Creating Content Pages

With the Master Page (Site.master) created, you are now ready to create ASP.NET Web Pages that are linked to this Master Page. These are known as Content Pages. Let's create three Content Pages: Home.aspx, Mission.aspx, and About.aspx.

  1. Adding a Content Page:

    • Open the "Add New Item" window.

    • Select the "Web Form with Master Page" template.

    • Name it Home.aspx and click "Add".

    • In the "Select a Master Page" dialog box, choose Site.master.

This will create a Content Page that includes a Page directive pointing to its Master Page. The Content Page will also contain Content controls that correspond to the ContentPlaceHolder controls in the Master Page.

For example, the initial code in Home.aspx will look like this:

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Home.aspx.cs" Inherits="ControlsDemo.Home" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"></asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="body" runat="server"></asp:Content>
  1. Customizing the Content Page:

    • Set the Title attribute to "Home Page".

    • Add the following code within the Content controls to style the page and add content:

    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <style>
    p {
        text-align: justify; color: palevioletred; font-family: Arial; text-indent: 50px;
    }
    ol {
        color: cadetblue; background-color: burlywood;
    }
    </style>
    </asp:Content>

    <asp:Content ID="Content2" ContentPlaceHolderID="body" runat="server">
    <div style="background-color: aqua; color: coral;font-family:'Arial Unicode MS';font-size:larger;font-weight: bold">
        Home Page
    </div>
    <p>We have set the pace with online learning. Learn what you want, when you want, and practice with
    the instructor-led training sessions, on-demand video tutorials which you can watch and listen.</p>
    <ol>
        <li>150+ Online Courses</li>
        <li>UNLIMITED ACCESS</li>
        <li>EXPERT TRAINERS</li>
        <li>VARIETY OF INSTRUCTION</li>
        <li>ON-THE-GO LEARNING</li>
        <li>PASSIONATE TEAM</li>
        <li>TRAINING INSTITUTE OF CHOICE</li>
    </ol>
    </asp:Content>
  1. Creating Additional Content Pages:

    • Repeat the process to create Mission.aspx and About.aspx.

    • Set the titles as "Mission Page" for Mission.aspx and "About Page" for About.aspx.

    • Use the following code for each page:

Mission.aspx:

    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <style>
    p {
        text-align: justify; color: blue; font-family: Calibri; text-indent: 50px;
    }
    </style>
    </asp:Content>

    <asp:Content ID="Content2" ContentPlaceHolderID="body" runat="server">
    <div style="background-color: aqua; color: coral;font-family:'Arial Unicode MS';font-size:larger;font-weight: bold">
        Our Mission
    </div>
    <p>We appreciate you taking the time today to visit our website. Our goal is to give you an interactive tour of our
    new and used inventory, as well as allow you to conveniently get a quote, schedule a service appointment, or apply
    for financing. The search for a luxury car is filled with high expectations. Undoubtedly, that has a lot to do with the
    vehicles you are considering, but at Motors, we think you should also have pretty high expectations for your
    dealership.</p>
    </asp:Content>

About.aspx:

    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <style>
    p {
        text-align: justify; color: green; font-family: 'Agency FB'; text-transform: capitalize; text-indent: 50px;
    }
    </style>
    </asp:Content>

    <asp:Content ID="Content2" ContentPlaceHolderID="body" runat="server">
    <div style="background-color: aqua; color: coral;font-family:'Arial Unicode MS';font-size:larger;font-weight: bold">
        About Us
    </div>
    <p>NareshIT (Naresh i Technologies) is a leading Software Training Institute that provides a Job Guarantee Program
    through Nacre in Hyderabad, Chennai, Bangalore, Vijayawada, and across the world through Online Training services.
    Managed and led by IT professionals with over a decade of experience in leading MNC companies, we are renowned for our
    training approach that enables students to gain real-time exposure to cutting-edge technologies.</p>
    </asp:Content>
  1. Running the Content Pages:

    • Run any of the three Content Pages (Home.aspx, Mission.aspx, or About.aspx), and you will see how they integrate seamlessly with the Site.master Master Page.

    • Clicking on any menu item at the top will navigate to the corresponding page in the site.

ViewState:

Web applications are stateless, meaning they do not persist (save) data from one request to use in the next. In a stateless application, the server does not store any state about the client session.

To demonstrate this, add a new WebForm named HitCount.aspx and include the following code in the <div> tag:

<asp:Button ID="btnCount" runat="server" Text="Hit Count"/>
<br/>
<asp:Label ID="lblCount" runat="server" ForeColor="Red"/>

Next, go to the “HitCount.aspx.cs” file and write the following code:

Declarations:

int Count = 0;

Code under the Hit Count Button Click event:

Count += 1;
lblCount.Text = "Hit Count: " + Count;

Now, run the WebForm and click the button multiple times. You'll notice that it always displays the output as "Hit Count: 1". This happens because every time you click the button, the server creates a new instance of the page class, initializes Count to 0, increments it to 1, sends the output to the client machine, and then destroys the page instance. This process repeats every time you click the button, so the value of Count is always 1. This is called "stateless" behavior.

To overcome this problem, we use ViewState, which is a technique used to store user data on the page during the postback of a web page.

Syntax for storing a value in ViewState:

ViewState["Counter"] = value;  // value can be any object

Syntax for accessing a value from ViewState:

object value = ViewState["Counter"];

To fix the problem in our previous example, rewrite the code under the button click event as follows:

int Count;

// Check if there is already a value stored in ViewState
if (ViewState["Counter"] == null)
{
    Count = 1;  // Initialize Count to 1 if ViewState is null
}
else
{
    // Retrieve the value from ViewState, increment it by 1
    Count = (int)ViewState["Counter"] + 1;
}

// Store the updated Count value back into ViewState
ViewState["Counter"] = Count;

// Display the updated Count value in the label
lblCount.Text = "Hit Count: " + Count;

Note: Every ASP.NET server control also maintains the state of its values using a mechanism called ControlState, which holds the values of controls and restores them after a page postback.

Processing of a Web Page by the Web Server

When a client requests a page for the first time, ASPNET_ISAPI.dll on the Web Server handles the request. The server creates a new class ASP.hitcount_aspx that inherits from the class HitCount, which is defined in the HitCount.aspx.cs and HitCount.aspx.designer.cs files. The server then compiles this new class and loads the compiled code into memory. If a subsequent request (postback) is made to the same page, the server uses the already compiled code from memory, without recompiling the page, to start the page's life cycle.

Page Life Cycle

The life cycle of a page describes how a web page is processed on the server when a browser requests it. Below are the various stages in the life cycle of a page:

  1. Page Request: This happens before the page life cycle starts. When a user asks for a page, the server determines whether the page needs to be parsed and executed (thus beginning the life cycle) or whether a cached version of the page can be sent in response without processing the page.

  2. Start: During this stage, the page's properties such as Request and Response are created and set. The page also determines whether the request is a postback or a new request (GET) and sets the IsPostBack property accordingly. IsPostBack will be true if it’s a postback request or false if it’s the first (GET) request.

  3. Initialization: In this stage, all the controls on the page are created, and each control's UniqueID property is set.

  4. Load: If the current request is a postback, the control properties are loaded with information retrieved from ViewState (or ControlState).

  5. Validation:In this stage, any server-side validations that are required will be performed, setting the IsValid property of individual validator controls and then of the page.

  6. Event Handling: If the request is a postback, all the controls' corresponding event handlers are called (only if required), along with any cached events. On the first request, only page events will fire, whereas in a postback request, both page events and required control events will fire.

  7. Rendering: In this stage, the page is rendered, i.e., converted into HTML. Before rendering, ViewState and ControlState are saved for the page and all controls. During the rendering stage, the page calls the RenderControl method on each control and writes its output to the OutputStream object of the page's Response property.

  8. Unload: After the page has been rendered and the output is sent to the client, the page is ready to be discarded. The Unload event is raised, and at this stage, the Request and Response properties are destroyed, and cleanup is performed.

Series of Actions Between the First Request and Postback of a Page

AutoEventWireup Attribute of Page Directive

ASP.NET supports an automatic way to bind page events to their event handlers if the AutoEventWireup attribute of the Page directive is set to true (the default is true). This works provided that event handler names follow a naming convention, i.e., Page_<EventName> (e.g., Page_Load). However, if you set the attribute to false or do not follow the naming convention, then event handlers must be explicitly bound to their corresponding events in the constructor of the page, as follows:

public PageEvents()
{
    this.Load += Page_Load;
}

Thanks, for MVC go here().