DR. AJAY KUMAR PATHAK
ASSISTANT PROFESSOR
READ ALL THE NOTES CHAPTER WISE
SUBJECT NAME:- MJ–12 (Th):- WEB PROGRAMMING
FOR B. Sc. IT.
SEM 6 F.Y.U.G.P.
SUBJECT : MJ–12 (Th): WEB PROGRAMMING
(To be selected by the students from)
UNIT 4 (UNIT NAME):- ASP.NET
Objective: The objective of the course is to enable students to
· The objective of this course is to provide students with a comprehensive understanding of network security concepts and techniques. The course aims to develop students' skills in identifying network vulnerabilities, implementing security measures, and ensuring the confidentiality, integrity, and availability of networked systems.
Learning Outcome:- After completion of this course, a student will be able to–
· Understand the principles and concepts of network security.
· Identify potential security threats and vulnerabilities in networked systems.
· Implement security measures to protect network infrastructure.
· Apply encryption and authentication techniques to secure network communication.
· Analyze and respond to security incidents in networked environments
Semester Examination and Distribution of Marks
INTERNAL MARKS :- 25 (NO PRACTICAL IN THE MJ 12 (WEB PROGRAMMING)
End Semester Examination (ESE) : 75 Marks
-: NOTES READ FROM HERE :-
SYLLABUS OF UNIT 4 :- ASP .NET: Building Web Forms Using ASP .NET, Exploring ASP .NET Server Controls, Using ASP.NET Server Controls to Create Web Forms, Understanding the Code behind the Page. Working with User Controls, Exposing User Control Properties and Methods, Using ASP .NET Server Controls in User Controls, Using Validation Controls to Improve Web Forms, Uploading Files to a Web Server.
UNIT- 4 :- ASP.NET
Introduction to
ASP.NET:- ASP.NET is a web application
framework designed and developed by Microsoft. ASP.NET is open source and a
subset of the .NET Framework and successor of the classic ASP(Active Server
Pages). With version 1.0 of the .NET Framework, it was first released in January
2002. So a question comes to mind that which technology we were using before
the year 2002 for developing web applications and services? Answer is Classic
ASP. So before .NET and ASP.NET there was Classic ASP.ASP.NET is built on the
CLR(Common Language Runtime) which allows the programmers to execute its code
using any .NET language(C#, VB etc.). It is specially designed to work with
HTTP and for web developers to create dynamic web pages, web applications, web
sites, and web services as it provides a good integration of HTML, CSS, and
JavaScript..NET Framework is used to create a variety of applications and
services like Console, Web, and Windows, etc. But ASP.NET is only used to
create web applications and web services. That’s why we termed ASP.NET as a
subset of the .NET Framework.
ASP.NET is a web development
platform, which provides a programming model, a comprehensive software
infrastructure and various services required to build up robust web
applications for PC, as well as mobile devices.ASP.NET works on top of the HTTP
protocol, and uses the HTTP commands and policies to set a browser-to-server
bilateral communication and cooperation.ASP.NET is a part of Microsoft .Net
platform. ASP.NET applications are compiled codes, written using the extensible
and reusable components or objects present in .Net framework. These codes can
use the entire hierarchy of classes in .Net framework.
The ASP.NET application codes
can be written in any of the following languages:-
• C#
• Visual Basic.Net
• Jscript
• J#
ASP.NET is used to produce
interactive, data-driven web applications over the internet. It consists of a
large number of controls such as text boxes, buttons, and labels for
assembling, configuring, and manipulating code to create HTML pages.
COMPONENTS OF .NET
FRAMEWORK 3.5:-
Before going to the next
session on Visual Studio.Net, let us go through at the various components of
the .Net framework 3.5. The following table describes the components of the .Net
framework 3.5 and the job they perform:-
Components and their
Description
(1) Common Language Runtime or CLR :- It performs memory management, exception handling,
debugging, security checking, thread execution, code execution, code safety,
verification, and compilation. The code that is directly managed by the CLR is
called the managed code. When the managed code is compiled, the compiler
converts the source code into a CPU independent intermediate language (IL)
code. A Just In Time(JIT) compiler compiles the IL code into native code, which
is CPU specific.
(2) .Net Framework Class Library:- It contains a huge library of reusable types. classes,
interfaces, structures, and enumerated values, which are collectively called
types.
(3) Common Language Specification:- It contains the specifications for the .Net supported
languages and implementation of language integration.
(4) Common Type System:- It provides guidelines for declaring, using, and
managing types at runtime, and cross-language communication.
(5) Metadata and Assemblies:- Metadata is the binary information describing the
program, which is either stored in a portable executable file (PE) or in the
memory. Assembly is a logical unit consisting of the assembly manifest, type
metadata, IL code, and a set of resources like image files.
(6) Windows Forms:- Windows Forms contain the graphical representation of
any window displayed in the application.
(7) ASP.NET and ASP.NET AJAX ( Full form
:Asynchronous JavaScript and XML):- ASP.NET
is the web development model and AJAX is an extension of ASP.NET for developing
and implementing AJAX functionality. ASP.NET AJAX contains the components that
allow the developer to update data on a website without a complete reload of
the page.
(8) ADO.NET:- It is the technology used for working with data and databases. It
provides access to data sources like SQL server, OLE DB, XML etc. The ADO.NET
allows connection to data sources for retrieving, manipulating, and updating
data.
(9) Windows Workflow Foundation (WF):- It helps in building workflow-based applications in Windows.
It contains activities, workflow runtime, workflow designer, and a rules
engine.
(10) Windows Presentation Foundation:- It provides a separation between the user interface
and the business logic. It helps in developing visually stunning interfaces
using documents, media, two and three dimensional graphics, animations, and
more.
(11) Windows Communication Foundation (WCF):- It is the technology used for building and executing
connected systems.
(12) Windows CardSpace:- It provides safety for accessing resources and sharing
personal information on the internet.
(13) LINQ:- It
imparts data querying capabilities to .Net languages using a syntax which is
similar to the tradition query language SQL.
ASP.NET provides an abstraction
layer on top of HTTP on which the web applications are built. It provides
high-level entities such as classes and components within an object-oriented
paradigm.
The key development tool for
building ASP.NET applications and front ends is Visual Studio. In this
tutorial, we work with Visual Studio 2008.
Visual Studio is an integrated
development environment for writing, compiling, and debugging the code. It
provides a complete set of development tools for building ASP.NET web
applications, web services, desktop applications, and mobile applications.
The Visual Studio IDE:-
The new project window allows
choosing an application template from the available templates.
When you start a new web site, ASP.NET
provides the starting folders and files for the site, including two files for
the first web form of the site.
The file named
Default.aspx contains the HTML and
asp code that defines the form,
and the file named Default.aspx.cs
(for C# coding) or the file named Default.aspx.vb (for VB coding) contains the
code in the language you have chosen and this code is responsible for the
actions performed on a form.
The primary window in the Visual Studio IDE is the Web Forms
Designer window. Other supporting windows are the Toolbox, the Solution
Explorer, and the Properties window. You use the designer to design a web form,
to add code to the control on the form so that the form works according to your
need, you use the code editor.
Working with Views
and Windows :- You can work with windows in the following ways:
·
To change the Web
Forms Designer from one view to another, click on the Design or source button.
·
To close a
window, click on the close button on the upper right corner and to redisplay,
select it from the View menu.
·
To hide a window,
click on its Auto Hide button. The window then changes into a tab. To display
again, click the Auto Hide button again.
·
To change the
size of a window, just drag it.
Adding Folders and Files to
your Website
When a new web form is created,
Visual Studio automatically generates the starting HTML for the form and
displays it in Source view of the web forms designer. The Solution Explorer is
used to add any other files, folders or any existing item on the web site.
·
To add a standard
folder, right-click on the project or folder under which you are going to add
the folder in the Solution Explorer and choose New Folder.
·
To add an ASP.NET
folder, right-click on the project in the Solution Explorer and select the
folder from the list.
·
To add an
existing item to the site, right-click on the project or folder under which you
are going to add the item in the Solution Explorer and select from the dialog
box.
Projects and
Solutions:- A typical ASP.NET application
consists of many items: the web content files (.aspx), source files (.cs
files), assemblies (.dll and .exe files), data source files (.mdb files),
references, icons, user controls and miscellaneous other files and folders. All
these files that make up the website are contained in a Solution.
When a new website is created.
VB2008 automatically creates the solution and displays it in the solution
explorer.
Solutions may contain one or
more projects. A project contains content files, source files, and other files
like data sources and image files. Generally, the contents of a project are
compiled into an assembly as an executable file (.exe) or a dynamic link
library (.dll) file.
TYPICALLY A PROJECT
CONTAINS THE FOLLOWING CONTENT FILES:
·
Page file (.aspx)
·
User control
(.ascx)
·
Web service
(.asmx)
·
Master page
(.master)
·
Site map
(.sitemap)
·
Website configuration
file (.config) Building and Running a Project
You can execute an
application by:-
·
Selecting Start
·
Selecting Start
Without Debugging from the Debug menu,
·
pressing F5
·
Ctrl-F5
The program is built meaning,
the .exe or the .dll files are generated by selecting a command from the Build
menu.
ASP.NET INTRODUCES
TWO MAJOR FEATURES: WEB FORMS AND WEB SERVICES:-
(1) Web Forms:- Developers not familiar with Web development can spend a great deal of
time, for example, figuring out how to validate the e-mail address on a form.
You can validate the information on a form by using a client-side script or a
server-side script. Deciding which kind of script to use is complicated by the
fact that each approach has its benefits and drawbacks, some of which aren't
apparent unless you've done substantial design work. If you validate the form
on the client by using client-side JScript code, you need to take into
consideration the browser that your users may use to access the form. Not all
browsers expose exactly the same representation of the document to programmatic
interfaces. If you validate the form on the server, you need to be aware of the
load that users might place on the server. The server has to validate the data
and send the result back to the client. Web Forms simplify Web development to
the point that it becomes as easy as dragging and dropping controls onto a
designer (the surface that you use to edit a page) to design interactive Web
applications that span from client to server.
(2) Web Services:- A Web service is an application that exposes a
programmatic interface through standard access methods. Web Services are
designed to be used by other applications and components and are not intended
to be useful directly to human end users. Web Services make it easy to build
applications that integrate features from remote sources. For example, you can
write a Web Service that provides weather information for subscribers of your
service instead of having subscribers link to a page or parse through a file
they download from your site. Clients can simply call a method on your Web
Service as if they are calling a method on a component installed on their
system — and have the weather information available in an easy-to-use format
that they can integrate into their own applications or Web sites with no
trouble.
(3) Windows Forms:- Windows Forms is the name of a unified set of classes
that provides support for creating traditional desktop applications —
applications that have a graphical user interface (GUI). Windows Forms make it
easy to develop end-user applications using any .NET programming language.
Furthermore, through Visual Studio .NET, developers can easily design forms by
using drag-and-drop editing.
(4) Visual Studio .NET:- Visual Studio .NET fulfills the promise of a single
development environment for all languages. Visual Studio .NET simplifies
development in a mixed-language environment through features such as support
for end-to-end debugging across all programming languages; visual designers for
XML, HTML, data, and server-side code; and full IntelliSense support (statement
completion). Visual Studio .NET replaces the Visual Basic 6, Visual C++, and
Visual InterDev development environments. Visual Studio .NET is able to provide
this level of integration because it relies and builds on the facilities of the
.NET Framework. Designers for Web forms and Windows Forms enhance developer
productivity during the development cycle. Integration of deployment features
enhances productivity during post-deployment debugging.
FEATURES OF .NET:-
Now that we know some basics of
.NET, let us see what makes .NET a wonderful platform for developing modern
applications.
(1) Rich Functionality out of the box:- .NET framework provides a rich set of functionality
out of the box. It contains hundreds of classes that provide variety of
functionality ready to use in your applications. This means that as a developer
you need not go into low level details of many operations such as file IO,
network communication and so on.
(2) Easy development of web applications:- ASP.NET is a technology
available on .NET platform for developing dynamic and data driven web
applications. ASP.NET provides an event driven programming model (similar to
Visual Basic 6 that simplify development of web pages (now called as web forms)
with complex user interface. ASP.NET server controls provide advanced user
interface elements (like calendar and grids) that save lot of coding from
programmer’s side.
(3) OOPs Support:- The advantages of Object Oriented programming are well
known. .NET provides a fully object oriented environment. The philosophy of
.NET is – “Object is mother of all.” Languages like Visual Basic.NET now
support many of the OO features that were lacking traditionally. Even primitive
types like integer and characters can be treated as objects – something not
available even in OO languages like C++.
(4) Multi-Language Support:- Generally enterprises have varying skill sets. For
example, a company might have people with skills in Visual Basic, C++, and Java
etc. It is an experience that whenever a new language or environment is
invented existing skills are outdated. This naturally increases cost of
training and learning curve. .NET provides something attractive in this area.
It supports multiple languages. This means that if you have skills in C++, you
need not throw them but just mould them to suit
.NET environment. Currently
four languages are available right out of the box namely – Visual Basic.NET, C#
(pronounced as C-sharp), Jscript.NET and Managed C++ (a dialect of Visual C++).
There are many vendors that are working on developing language compilers for
other languages (20+ language compilers are already available). The beauty of
multi language support lies in the fact that even though the syntax of each
language is different, the basic capabilities of each language remain at par
with one another.
(5) Multi-Device Support:- Modern lift style is increasingly embracing mobile and
wireless devices such as PDAs, mobiles and handheld PCs NET provides promising platform for
programming such devices. .NET
Compact Framework and Mobile Internet Toolkit are step ahead in this direction.
(6) Automatic memory management:- While developing applications developers had to
develop an eye on system resources like memory. Memory leaks were major reason
in failure of applications. .NET takes this worry away from developer by
handling memory on its own. The garbage collector takes care of freeing unused
objects at appropriate intervals.
(7) Compatibility with COM and COM+ :- Before the introduction of .NET, COM was the de-facto
standard for componentized software development. Companies have invested lot of
money and efforts in developing COM components and controls. The good news is –
you can still use COM components and ActiveX controls under .NET. This allows
you to use your existing investment in .NET applications. .NET still relies on
COM+ for features like transaction management and object pooling. In fact it
provides enhanced declarative support for configuring COM+ application right
from your source code. Your COM+ knowledge still remains as a valuable asset.
(8) No more DLL Hell:- If you have worked with COM components, you probably
are aware of “DLL hell”. DLL conflicts are a common fact in COM world. The main
reason behind this was the philosophy of COM – “one version of component across
machine”. Also, COM components require registration in the system registry.
.NET ends this DLL hell by allowing applications to use their own copy of
dependent DLLs. Also, .NET components do not require any kind of registration
in system registry.
(9) Strong XML support:- Now days it is hard to find a programmer
who is unaware of XML. XML has gained such a strong industry support that
almost all the vendors have released some kind of upgrades or patches to their
existing software to make it “XML
compatible”. Currently, .NET is
the only platform that has built with XML right into the core framework. .NET
tries to harness power of XML in every possible way. In addition to providing
support for manipulating and transforming XML documents, .NET provides XML web
services that are based on standards like HTTP, XML and SOAP.
(10) Ease of deployment and configuration:- Deploying windows applications especially that used
COM components were always been a tedious task. Since .NET does not require any
registration as such, much of the deployment is simplified. This makes XCOPY
deployment viable. Configuration is another area where .NET – especially
ASP.NET – shines over traditional languages. The configuration is done via
special files having special XML vocabulary. Since, most of the configuration
is done via configuration files, there is no need to sit in front of actual
machine and configure the application manually. This is more important for web
applications; simply FTPing new configuration file makes necessary changes.
(11) Security:- Windows platform was always criticized for poor security mechanisms.
Microsoft has taken great efforts to make .NET platform safe and secure for
enterprise applications. Features such as type safety, code access security
etc.
BUILDING WEB FORMS USING
ASP.NET OR CREATING WEB FORMS IN ASP NET USING C#:-
Introduction:- Active Server Pages (ASP) and Active Server Pages
(ASP.NET) are server-side technologies for displaying interactive web pages.
ASP.NET offers developers a wide range of options in a large, diverse ecosystem
of libraries and tools. Developers can also design custom libraries that can be
shared with any .NET platform application.
ASP.NET also contains an
authentication system for developers, which includes a database, libraries, templates
for handling logins, external authentication to Google, Facebook, and other
services, and more. ASP.NET may be used on all major platforms, including
Windows, Linux, macOS, and even Docker, by developers.
ASP.NET Web Forms:- Web Forms are pages which are requested by your users
through their browser. HTML, client-script, server controls, and server code
can all be used to create these pages. When users request a page, the framework
compiles and executes it on the server, then generates the HTML markup that the
browser may render. In any browser or client device, an ASP.NET Web Forms page
displays information to the user.
ASP.NET Web Forms may be
created with Visual Studio. Drag and drop server controls to set out your Web
Forms page in the Visual Studio Integrated Development Environment (IDE). The
methods, properties, and events for controls on the page, as well as the page
itself, can then be readily set. These attributes, methods, and events are used
to define the behaviour, appearance, and feel of a web page, among other
things. We can use .NET language like Visual Basic or C# to develop server code
to handle the page's logic.
STEPS TO CREATE A WEB
FORM :-
1ST STEP:-
Creating
an ASP.NET Web Forms Project,
Let's get started with the
creation of ASP.NET Web Forms project as shown in the images below.
Firstly create a new project.
START,
ASP.NET EMPTY
WEB APPLICATION,
SEE BELOW
SCREN SHOT
STEP 2:- Choose Web Forms Template
Select Web Forms, Click Create
STEP 3:- Add a New Web Form
Right-click on project → Add →
Web Form, Name it: Form1.aspx
STEP 4: Design the Web Form (UI):-
Open Design View, Drag &
Drop controls from Toolbox:-
Label
TextBox
Button
STEP 5:- Write ASPX Code
Example:-
<%@ Page
Language="C#" AutoEventWireup="true"
CodeFile="Form1.aspx.cs" Inherits="Form1" %>
<!DOCTYPE html>
<html>
<head
runat="server">
<title>Simple Form</title>
</head>
<body>
<form id="form1"
runat="server">
<div>
Name:
<asp:TextBox
ID="txtName" runat="server"></asp:TextBox>
<br /><br />
<asp:Button
ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<br /><br />
<asp:Label
ID="lblMessage" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
STEP 6:- Write C# Code (Code-Behind):-
Open Form1.aspx.cs
using System;
public partial class Form1 :
System.Web.UI.Page
{
protected void btnSubmit_Click(object
sender, EventArgs e)
{
string name = txtName.Text;
lblMessage.Text = "Hello " +
name + "!";
}
}
STEP 7:- Run the Project:-
Press F5 or click Start, Browser
will open, Enter name → Click Submit → Output will display
STEP 8:- FINAL OUTPUT
User enters name,
Clicks button,
Message shows:-
OUTPUT:- Hello Ajay!
EXPLORING ASP.NET
SERVER CONTROLS:-
ASP.NET server controls are
components used to build user interfaces in web applications, which can be
programmed using C# on the server side. When a page is rendered, these controls
generate standard HTML elements that are sent to the client browser.
COMMON ASP.NET SERVER
CONTROL CATEGORIES:-
ASP.NET provides a wide range
of built-in server controls:
(1) Standard Controls:- Basic form elements
like TextBox, Button, Label, CheckBox, and HyperLink.
(2) List Controls:- Controls for displaying data in lists and
allowing selection, such as DropDownList, ListBox, CheckBoxList,
and RadioButtonList.
(3) Validation Controls:- Used to validate user input without
extensive client-side JavaScript, including RequiredFieldValidator, RangeValidator,
and RegularExpressionValidator.
(4) Data Controls:- Powerful controls
like GridView, DetailsView, and Repeater for binding to
data sources (e.g., databases) and displaying data in customizable formats.
(5) Rich Controls:- Specialized controls that offer complex
functionality, such as
the Calendar and FileUpload controls.
(6) Navigation Controls:- Used to create menus and sitemaps,
like Menu and TreeView controls.
(7) Login Controls:- Pre-built controls to handle user
authentication, including Login and LoginStatus.
(1) HTML SERVER CONTROLS:-
The HTML server controls are
HTML elements that include a runat=server attribute. The HTML server controls
have the same HTML output and the same properties as their corresponding HTML
tags. In addition, HTML server controls provide automatic state management and
server-side events. HTML server controls offer the following advantages:-
i.
The HTML server
controls map one to one with their corresponding HTML tags.
ii. When the ASP.NET application is compiled, the HTML
server controls with the runat=server attribute are compiled into the assembly.
iii. Most controls include an OnServerEvent for the most
commonly used event for the control. For example, the <input type=button>
control has an OnServerClick event.
iv. The HTML tags that are not implemented as specific
HTML server controls can still be used on the server side; however, they are
added to the assembly as HtmlGenericControl.
v. When the ASP.NET page is reposted, the HTML server
controls keep their values.
To use an HTML server control,
use the following syntax (which uses the HtmlInputText control as an example):-
ASP.NET (C #)
<input type="text"
value="hello world" runat=server />
HTML server controls that are
available in ASP.NET,
see the following Web sites:-
(i) HtmlButton Control:- Creates a server-side control that maps to the
<button> HTML element and allows you create push buttons.
<button
id="programmaticID"
OnServerClick="onserverclickhandler"
runat="server" >
buttontext, image, or control
</button>
Remarks :- Use the HtmlButton
control to program against the HTML <button> element. You can provide
custom code for the ServerClick event of the HtmlButton control to specify the
action performed when the control is clicked.
(ii) HtmlForm Control:- Creates a server-side control that maps to the
<form> HTML element and allows you to create a container for elements in
a Web page.
<form
id="programmaticID"
method=POST | GET
action="srcpageURL"
runat="server" >
Other controls, input forms, and so on.
</form>
Remarks :- Use the HtmlForm control to program against
the HTML <form> element. To take advantage of the postback services, all
Web Forms controls, whether HTML, Web, pagelet, or custom, must be nested between
well-formed opening and closing tags of the HtmlForm control. If the tags are
not closed properly, ASP.NET will not recognize the element. The element will
either be ignored or a compilation error will occur, depending on how the
element is formed.
(iii) HtmlInputButton Control:- Creates a server-side control that maps to the
<input type=button>, <input type=submit>, and <input
type=reset> HTML elements and allows you to create a command button, submit
button, or reset button, respectively.
<input type=button | submit
| reset
id="programmaticID"
OnServerClick="onserverclickhandler"
runat="server" >
Remarks:- Use the
HtmlInputButton control to program against the <input type=button>,
<input type=submit>, and <input type=reset> HTML elements. When a
user clicks an HtmlInputButton control, input from the form that the control is
embedded on is posted to the server and processed. A response is then sent back
to the requesting browser.
(iv) HtmlInputCheckBox Control:- Creates a server-side control that maps to the
<input type=checkbox> HTML element and allows you to a create check box
control that lets the user select a true or false state.
<input type=checkbox
id="programmaticID"
checked
runat="server" >
Remarks:- Use the
HtmlInputCheckBox control to program against the <input type=checkbox>
HTML element. The HtmlInputCheckBox control does not post back to the server
when it is clicked. The state of the check box is sent to the server for
processing when you use a control that posts back the server, such as the
HtmlInputButton control. To determine whether the check box is selected, test
the Checked property of the control.
Note This control does not require a closing tag.
(v) HtmlInputRadioButton Control:- Creates a server-side control that maps to the
<input type=radio> HTML element and allows you to create a radio button
on a Web page.
<input type=radio
id="programmaticID"
checked
name="radiobuttongroup"
runat="server" >
Remarks:- Use the
HtmlInputRadioButton control to program against the HTML <input
type=radio> element. You can group multiple HtmlInputRadioButton controls
together by setting the Name property to a value that is common to all
<input type=radio> elements within the group. Radio buttons in the same
group are mutually exclusive; only one radio button in the group can be
selected at a time.
Note This control does not require a closing tag.
(vi) HtmlInputText Control:- Creates a server-side control that maps to the <input
type=text> and <input type=password> HTML elements and allows you to
create a single line text box to receive user input.
<input type=text | password
id="programmaticID"
maxlength="max#ofcharacters"
size="widthoftextbox"
value="defaulttextboxcontents"
runat="server" >
Remarks:- Use the HtmlInputText
control to run server code against the <input type=text> and <input
type=password> HTML elements. As with standard HTML, these controls can be
used to enter user names and passwords in HTML forms.
Note When the Type property is set to password,
your entry is masked in the text box.
(2) WEB SERVER CONTROLS:- Web controls are similar to the HTML server controls
such as Button, TextBox, and Hyperlink, except that Web controls have a
standardized set of property names. Web server controls offer the following
advantages:-
The
System.Web.UI.WebControls.WebControl base class contains all of the common
properties. Most of the Web server controls derive from this class.
Web server controls can be
divided into four categories:-
i.
Basic Web
Controls
ii. Validation Controls
iii. List Controls
iv. Rich Controls
(I) BASIC WEB CONTROLS:- Basic Web controls provide the same functionality as
their HTML server control counterparts. However, basic Web controls include
additional methods, events, and properties against which you can program.
Web controls that are available
in ASP.NET, see the following Web sites:-
(i) Button Web Server Control:- Displays
a push button control on the Web Forms page.
<asp:Button
id="MyButton"
Text="label"
CommandName="command"
CommandArgument="commandargument"
CausesValidation="true | false"
OnClick="OnClickMethod"
runat="server"/>
Remarks:- The Button control
allows you to create a push button on the Web Forms page. There are two types
of buttons that can be created. You can create either a submit button or a
command button.
(ii) CheckBox Web Server Control:- Creates a check box control that allows the user to
switch between a true or false state.
<asp:CheckBox
id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
Remarks:- The CheckBox control
creates a check box on the Web Forms page that allows the user to switch
between a true or false state. You can specify the caption to display in the
control by setting the Text property. The caption can appear either on the
right or left of the check box. Set the TextAlign property to specify the side
that the caption appears on.
Note:- Because the <asp:CheckBox> element has
no content, you can close the tag with /> instead of using a separate
closing tag.
(iii) Label Web Server Control:- Displays static text on a Web Forms page and allows
you to manipulate it programmatically.
<asp:Label
id="Label1"
Text="label"
runat="server"/>
or
<asp:Label
id="Label1"
runat="server">
Text
</asp:Label>
Remarks:- Use the Label control
to display text in a set location on the page. Unlike static text, you can
customize the displayed text by setting the Text property.
(iv) LinkButton Web Server Control:- Creates a hyperlink-style button on a Web Forms page.
<asp:LinkButton
id="LinkButton1"
Text="label"
Command="Command"
CommandArgument="CommandArgument"
CausesValidation="true | false"
OnClick="OnClickMethod"
runat="server"/>
or
<asp:LinkButton
id="LinkButton1"
Command="Command"
CommandArgument="CommandArgument"
CausesValidation="true | false"
OnClick="OnClickMethod"
runat="server"/>
Text
</asp:LinkButton>
Remarks:- Use the LinkButton
control to create a hyperlink-style button on a Web Forms page. Specify the
text to display in the LinkButton control by either setting the Text property
or placing the text between the opening and closing tags of the LinkButton
control. You can create either a submit button or a command button.
(v) RadioButton Web Server Control:- Creates an individual radio button on the page. You
can group multiple radio buttons together to provide a mutually exclusive set
of choices.
<asp:RadioButton
id="RadioButton1"
AutoPostBack="True|False"
Checked="True|False"
GroupName="GroupName"
Text="label"
TextAlign="Right|Left"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
Remarks:- The RadioButton
server control creates a radio button on the Web Forms page. Specify the text
to display in the control by setting Text property. The text can appear either
on the left or the right of the radio button. Set TextAlign property to control
the side that the text appears on. You can group multiple radio buttons
together if you specify the same GroupName for each RadioButton control.
Grouping radio buttons together will only allow a mutually exclusive selection
from the group.
(vi) TextBox Web Server Control:- Creates single-line and multiline text boxes.
<asp:TextBox
id="value"
AutoPostBack="True|False"
Columns="characters"
MaxLength="characters"
Rows="rows"
Text="text"
TextMode="SingleLine | MultiLine |
Password"
Wrap="True|False"
OnTextChanged="OnTextChangedMethod"
runat="server"/>
Remarks:- The TextBox server
control is an input control that lets the user enter text. By default, the
TextMode property is set to SingleLine, which creates a text box with only one
line. You can also set the property to MultiLine or Password. MultiLine creates
a text box with more than one line. Password creates a single-line text box
that masks the value entered by the user.
(vii) Image Web Server Control:- Displays a Web-compatible image on the Web Forms
page.
<asp:Image
id="Image1" runat="server"
ImageUrl="string"
AlternateText="string"
ImageAlign="NotSet|AbsBottom|AbsMiddle|BaseLine|
Bottom|Left|Middle|Right|TextTop|Top"/>
Remarks:-Use the Image control
to display an image on the Web Forms page. Setting the ImageUrl property
specifies the path to the displayed image. You can specify the text to display
in place of the image when the image is not available by setting the
AlternateText property. The ImageAlign property specifies the alignment of the
image in relation to other elements on the Web Forms page.
(viii) HyperLink Web Server Control:- Creates a link on the page that users can click to
move to another page.
<asp:HyperLink
id="HyperLink1"
NavigateURL="url"
Text="HyperLinkText"
ImageUrl="url"
Target="window"
runat="server"/>
or
<asp:HyperLink
id="HyperLink1"""
NavigateURL="url"
ImageUrl="url"
Target="window"
runat="server">
Text
</asp:HyperLink>
Remarks:- Use the HyperLink
control to create a link that moves you to another page or location on the
page. Specify the page or location to link to by using the NavigateURL
property. The link can either be displayed as text or an image. To display
text, either set the Text property or simply place the text between the opening
and closing tags of the HyperLink control. To display an image, set the
ImageUrl property.
(ix) ImageButton Web Server Control:- Enables you to handle user clicks in an image, which
gives you functionality similar to an image map.
<asp:ImageButton
id="ImageButton1"
ImageUrl="string"
Command="Command"
CommandArgument="CommandArgument"
CausesValidation="true | false"
OnClick="OnClickMethod"
runat="server"/>
Remarks:- Use the ImageButton
control to display an image that responds to mouse clicks. Specify the image to
display in the control by setting the ImageUrl property.
Both the Click and Command
events are raised when the ImageButton control is clicked.
(2) VALIDATION CONTROLS:- Validation controls are used to validate the values
that are entered into other controls of the page. Validation controls perform
client-side validation, server-side validation, or both, depending on the
capabilities of the browser in which the page is displayed. Validation controls
offer the following advantages:-
(i) RequiredFieldValidator control:- The RequiredFieldValidator control ensures that the
user does not skip a required entry field.
A RequiredFieldValidator works
in conjunction with another control, for example a TextBox control. Add the
control you want to validate to your page before you add the
RequiredFieldValidator so that you can easily associate the
RequiredFieldValidator with it.
To add a RequiredFieldValidator
control to a page
i.
Drag the
RequiredFieldValidator control from the Toolbox task pane to your page.
ii. Select the RequiredFieldValidator in Design view,
right-click it, and click Properties on the shortcut menu.
iii. In the Tag Properties task pane, select the control
you want to validate with the RequiredFieldValidator in the ControlToValidate
property dropdown.
iv. Set the ErrorMessage property to the text you want to
be displayed when a user leaves the control blank.
v. If you are going to use a ValidationSummary control to
consolidate validation error messages, set the ValidationGroup property to the
name of the group of validation controls. This can be any string, as long as
all the controls in the group have the same value.
vi. For a full description of all RequiredFieldValidator
control properties, see RequiredFieldValidator Members in the MSDN library.
(ii) RangeValidator control:- The RangeValidator control checks that a user's entry
is between specified lower and upper boundaries. You can check ranges within
pairs of numbers, alphabetic characters, and dates.
A RangeValidator works in
conjunction with another control, for example a TextBox control. Add the
control you want to validate to your page before you add the RangeValidator so
that you can easily associate the RangeValidator with it.
To add a RangeValidator control
to a page
i.
Drag the
RangeValidator control from the Toolbox task pane to your page.
ii. Select the RangeValidator in Design view, right-click
it, and click Properties on the shortcut menu.
iii. In the Tag Properties task pane, select the control
you want to validate with the RangeValidator in the ControlToValidate property
dropdown.
iv. Set the MaximumValue and MinimumValue properties to
the highest and lowest values, respectively, that you want to allow a user to
enter into the control you are validating.
v. If you are going to use a ValidationSummary control to
consolidate validation error messages, set the ValidationGroup property to the
name of the group of validation controls. This can be any string, as long as
all the controls in the group have the same value.
vi. For a full description of all RangeValidator control
properties, see RangeValidator Members in the MSDN library.
vii. For more information about using validation controls
to validate user input, see How-to Topics — Validation Controls in the MSDN
library.
(iii) CompareValidator control:- The CompareValidator control compares a user's entry
against a constant value, against the value of another control (using a
comparison operator such as less than, equal, or greater than), or for a
specific data type.
A CompareValidator works in
conjunction with another control, for example a TextBox control. Add the
control you want to validate to your page before you add the CompareValidator
so that you can easily associate the CompareValidator with it.
To add a CompareValidator
control to a page
i.
Drag the
CompareValidator control from the Toolbox task pane to your page.
ii. Select the CompareValidator in Design view,
right-click it, and click Properties on the shortcut menu.
iii. In the Tag Properties task pane, select the control
you want to validate with the CompareValidator in the ControlToValidate
property dropdown.
iv. Set the ControlToCompare or ValueToCompare property to
the control or value that you want to compare.
v. Set the Operator property to the comparison you want
to use: Equal, NotEqual, GreaterThan, GeaterThanEqual, LessThan, LessThanEqual,
or DataTypeCheck. For information about these operators, see
CompareValidator.Operator Property in the MSDN library.
vi. If you are going to use a ValidationSummary control to
consolidate validation error messages, set the ValidationGroup property to the
name of the group of validation controls. This can be any string, as long as
all the controls in the group have the same value.
(iv) RegularExpressionValidator control:- The RegularExpressionValidator control checks that the
entry matches a pattern defined by a regular expression. This type of
validation enables you to check for predictable sequences of characters, such
as those in e-mail addresses, telephone numbers, postal codes, and so on.
A RegularExpressionValidator
works in conjunction with another control, for example a TextBox control. Add
the control you want to validate to your page before you add the
RegularExpressionValidator so that you can easily associate the
RegularExpressionValidator with it.
To add a
RegularExpressionValidator control to a page
i.
Drag the
RegularExpressionValidator control from the Toolbox task pane to your page.
ii. Select the RegularExpressionValidator in Design view,
right-click it, and click Properties on the shortcut menu.
iii. In the Tag Properties task pane, select the control
you want to validate with the RegularExpressionValidator in the
ControlToValidate property dropdown.
iv. Set the ValidationExpression property to the regular
expression that the text in the control must match to be valid.
(v) CustomValidator control:- The CustomValidator control checks the user's entry
using validation logic that you write yourself. This type of validation enables
you to check for values derived at run time.
A CustomValidator works in
conjunction with another control, for example a TextBox control. Add the
control you want to validate to your page before you add the CustomValidator so
that you can easily associate the CustomValidator with it.
To add a
CustomValidator control to a page
i.
Drag the
CustomValidator control from the Toolbox task pane to your page.
ii. Select the CustomValidator in Design view, right-click
it, and click Properties on the shortcut menu.
iii. In the Tag Properties task pane, select the control
you want to validate with the CustomValidator in the ControlToValidate property
dropdown.
iv. To validate the control in the client browser, set the
ClientValidationFunction to the name of the JavaScript function to use in
validation.
v. For information about writing a client or server
function for use with the CustomValidator control, see How to: Validate with a
Custom Function for ASP.NET Server Controls in the MSDN library.
vi. If you are going to use a ValidationSummary control to
consolidate validation error messages, set the ValidationGroup property to the
name of the group of validation controls. This can be any string, as long as
all the controls in the group have the same value.
vii. For a full description of all CustomValidator control
properties, see CustomValidator Members in the MSDN library.
viii.For more information about using validation controls
to validate user input, see How-to Topics — Validation Controls in the MSDN
library.
(vi) ValidationSummary control:- The ValidationSummary class is used to summarize the
error messages from all validators on a web page in a single location.
i.
Drag the
ValidationSummary control from the Toolbox task pane to your page.
ii. Select the ValidationSummary in Design view,
right-click it, and click Properties on the shortcut menu.
iii. Set the ValidationGroup property to the name of the
group of validation controls. This can be any string, as long as all the
controls in the group have the same value.
iv. The summary can be displayed as a list, as a bulleted
list, or as a single paragraph, based on the DisplayMode property. The summary
can be displayed on the web page and in a message box by setting the
ShowSummary and ShowMessageBox properties, respectively.
v. For a full description of all ValidationSummary
control properties, see ValidationSummary Members in the MSDN library.
vi. For more information about using validation controls
to validate user input, see How-to Topics — Validation Controls in the MSDN
library.
(3) LIST CONTROLS:- List controls are special Web server controls that
support binding to collections. You can use list controls to display rows of
data in a customized, template's format. All list controls expose DataSource
and DataMember properties, which are used to bind to collections.
List controls can bind only to
collections that support the IEnumerable, ICollection, or IListSource
interfaces. For example, a Visual C# .NET sample page appears as follows
(i) ListBox Web Server Control:- Creates a single-selection or multiselection list
box.
<asp:ListBox
id="Listbox1"
DataSource="<%
databindingexpression %>"
DataTextField="DataSourceField"
DataValueField="DataSourceField"
AutoPostBack="True|False"
Rows="rowcount"
SelectionMode="Single|Multiple"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod"
runat="server">
<asp:ListItem value="value"
selected="True|False">
Text
</asp:ListItem>
</asp:ListBox>
Remarks:- Use the ListBox
control to create a list control that allows single or multiple item selection.
Use the Rows property to specify the height of the control. To enable multiple
item selection, set the SelectionMode property to ListSelectionMode.Multiple.
(ii) CheckBoxList Web Server Control:- Creates a multiselection check box group. This
control supports binding to a data source.
Remarks:- The CheckBoxList
control creates a multiselection check box group that can be dynamically
generated using data binding. To specify items that you want to appear in the
CheckBoxList control, place a ListItem element for each entry between the
opening and closing tags of the CheckBoxList control.
Note You can also use multiple CheckBox controls.
The CheckBoxList control is easier for creating a set of check boxes using data
binding, while the individual CheckBox control gives you greater control over
layout.
(iii) RadioButtonList Web Server Control:- Creates a group of radio buttons. This control
supports binding to a data source.
Remarks: -The RadioButtonList
control allows you to create a single-selection radio button group that can be
dynamically generated by binding to a data source. To specify the items that
you want to appear in the RadioButtonList control, place a ListItem element for
each entry between the opening and closing tags of the RadioButtonList control.
Note You can also use the RadioButton control.
The RadioButtonList control is easier for creating a set of radio buttons using
data binding, while an individual RadioButton control gives you greater control
over layout.
(iv) DataList Web Server Control:- Displays the items from a data source by using
templates. You can customize the appearance and contents of the control by
manipulating the templates that make up the different components of the
DataList control, such as the ItemTemplate and HeaderTemplate.
Remarks:- You can manipulate
the control's layout and content by defining templates. The following table
lists the different templates for the DataList control.
(v) DataGrid Web Server Control:- The DataGrid control renders a tabular, data-bound
grid. This control allows you to define various types of columns to control the
layout of the cell contents of the grid (bound columns, template columns) and
add specific functionality (such as edit button columns, hyperlink columns, and
so on). The control also supports a variety of options for paging through data.
Remarks:- The DataGrid control
displays the fields of a data source as columns in a table. Each row in the
DataGrid control represents a record in the data source. The DataGrid control
supports selection, editing, deleting, paging, and sorting.
(vi) DropDownList Web Server Control:-- Enables users to select from a single-selection
drop-down list. The drop-down list can contain any number of items.
Remarks:- Use the DropDownList
control to create a single selection drop-down list control. You can control
the appearance of the DropDownList control by setting the BorderColor,
BorderStyle, and BorderWidth properties.
(4) RICH CONTROLS:- In addition to the preceding controls, the ASP.NET
page framework provides a few, task-specific controls called rich controls.
Rich controls are built with multiple HTML elements and contain rich
functionality. Examples of rich controls are the Calendar control and the
AdRotator control.
For more information about
individual rich controls that are available in ASP.NET, see the following Web
sites:-
(i) AdRotator Web Server Control:- Displays an advertisement banner on a Web Forms page.
<asp:AdRotator
id="Value"
AdvertisementFile="AdvertisementFile"
KeyWordFilter="KeyWord"
Target="Target"
OnAdCreated="OnAdCreatedMethod"
runat="server"/>
|
Element |
Description |
|
<ImageUrl> |
The absolute or relative URL
to an image file (optional). |
|
<NavigateURL> |
The URL of a page to link to
if the user clicks the ad (optional). Note If this
element is not set, the HRef property is not rendered on the anchor
tag. |
|
<AlternateText> |
The text display in place of
the image when the image specified by the ImageUrl property is not
available (optional). In some browsers, this text
also appears as a ToolTip for the advertisement. |
|
<Keyword> |
A category for the
advertisement (for example, "computers") that you can filter
by (optional). |
|
<Impressions> |
A number that indicates the
importance of the ad in the schedule of rotation relative to the other ads in
the file (optional). The larger the number, the
more often the ad is displayed. The total of all Impressions values
in the XML file cannot exceed 2,047,999,999. If it does,
the AdRotator throws a run-time exception. |
Remarks:- The AdRotator control
displays an advertisement banner on a Web Forms page. It displays the image
specified by the ImageUrl element within an anchor control. At run time, the
AdRotator control uses <asp:HyperLink> and <asp:Image> controls to
render the control on the Web Forms page. The source image is sized by the
browser to the dimensions of the AdRotator control, regardless of its actual
size.
(ii) Calendar Web Server Control:- Displays a one-month calendar that allows the user to
select dates and move to the next or previous month.
Remarks:- The Calendar control
is used to display a one-month calendar that allows the user to select dates
and move to the next and previous months.
|
Style object |
Description |
Style class |
|
The style for the section of
the calendar where the names of the days of the week appear. |
||
|
The style for the individual
days in the displayed month. Note Weekends, the current date, and
the selected day can have different styles by setting the WeekendDayStyle, TodayDayStyle,
and SelectedDayStyle properties, respectively. |
||
|
The style for the sections at
the left and right ends of the title bar where the month navigation LinkButton controls
are located. |
||
|
The style for the days from
the previous and next month that appear on the current month view. |
||
|
The style for the selected
date. Note If this property is not set, the
style specified by the DayStyle property is used to display
the selected date. |
||
|
The style for the column on
the left of the Calendar control containing links for
selecting a week or the entire month. |
||
|
The style for the title bar
at the top of the calendar containing the month name and month navigation
links. Note If NextPrevStyle is
set, it overrides the style for the next and previous month navigation
controls located at the ends of the title bar. |
||
|
The style for the current
date. Note If this property is not set, the
style specified by the DayStyle property is used to display the
current date. |
||
|
The style for the weekend
days. Note If this property is not set, the
style specified by the DayStyle property is used to display
the weekend dates. |
(iii) Xml Web Server
Control:- Displays an XML document or the
results of an XSL Transform.
Remarks:- Use the Xml control
to display the contents of an XML document or the results of an XSL Transform.
|
Property |
Description |
|
Sets the XML document using
a System.Xml.XmlDocument object. |
|
|
Sets the XML document using a
string. Note This property is commonly set
declaratively by placing text between the opening and closing <asp:Xml> tags
of the Xml control. |
|
|
Sets the XML document using a
file. |
USING ASP.NET SERVER
CONTROLS TO CREATE WEB FORM:-
INTRODUCTION:- ASP.NET Web Forms is a framework in Microsoft ASP.NET
used to build dynamic web applications. Server Controls are special controls
(like TextBox, Button, Label) That:- Run on the server, Automatically handle
events, Generate HTML dynamically
ANSWER ALL STEPS:-
(1) REQUIREMENTS:- Before starting, install, Visual Studio (recommended), .NET Framework / ASP.NET
(2) STEP-BY-STEP PROCEDURE:- Open Visual
Studio, Click Create New Project
(3) Select Project:- Choose ASP.NET Web Application (.NET Framework), Click
Next
(4) Configure Project:- Project Name: StudentFormApp, Click Create
(5) Select Template:- Choose Web Forms, Click Create
(6) Add Web Form:- Right-click project → Add → Web Form, Name:
StudentForm.aspx
(7) DESIGN WEB FORM (ASPX CODE):- This form includes, Name, Address, Age, Mobile, Gender,
Course
(8) CODE OF ASPX
</>aspx
<%@ Page
Language="C#" AutoEventWireup="true"
CodeFile="StudentForm.aspx.cs" Inherits="StudentForm" %>
<!DOCTYPE html>
<html>
<head
runat="server">
<title>Student Registration
Form</title>
</head>
<body>
<form id="form1"
runat="server">
<h2>Student Registration
Form</h2>
<!-- Name -->
<asp:Label ID="lblName"
runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName"
runat="server"></asp:TextBox>
<br /><br />
<!-- Address -->
<asp:Label ID="lblAddress"
runat="server" Text="Address:"></asp:Label>
<asp:TextBox
ID="txtAddress" runat="server"
TextMode="MultiLine"></asp:TextBox>
<br /><br />
<!-- Age -->
<asp:Label ID="lblAge"
runat="server" Text="Age:"></asp:Label>
<asp:TextBox ID="txtAge"
runat="server"></asp:TextBox>
<br /><br />
<!-- Mobile -->
<asp:Label ID="lblMobile"
runat="server" Text="Mobile:"></asp:Label>
<asp:TextBox
ID="txtMobile" runat="server"></asp:TextBox>
<br /><br />
<!-- Gender -->
<asp:Label ID="lblGender"
runat="server" Text="Gender:"></asp:Label>
<asp:RadioButton
ID="rbMale" runat="server" Text="Male"
GroupName="gender" />
<asp:RadioButton
ID="rbFemale" runat="server" Text="Female"
GroupName="gender" />
<br /><br />
<!-- Course -->
<asp:Label ID="lblCourse"
runat="server" Text="Course:"></asp:Label>
<asp:DropDownList
ID="ddlCourse" runat="server">
<asp:ListItem>BCA</asp:ListItem>
<asp:ListItem>MCA</asp:ListItem>
<asp:ListItem>B.Tech</asp:ListItem>
</asp:DropDownList>
<br /><br />
<!-- Button -->
<asp:Button ID="btnSubmit"
runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<br /><br />
<!-- Output -->
<asp:Label ID="lblResult"
runat="server" ForeColor="Green"></asp:Label>
</form>
</body>
</html>
(9) CODE-BEHIND (C#) (this code automatically
will generate )
</>c#
using System;
public partial class
StudentForm : System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
}
protected void btnSubmit_Click(object
sender, EventArgs e)
{
string name = txtName.Text;
string address = txtAddress.Text;
string age = txtAge.Text;
string mobile = txtMobile.Text;
string gender = "";
if (rbMale.Checked)
gender = "Male";
else if (rbFemale.Checked)
gender = "Female";
string course =
ddlCourse.SelectedItem.Text;
lblResult.Text = "Name: " +
name + "<br/>" +
"Address: "
+ address + "<br/>" +
"Age: " +
age + "<br/>" +
"Mobile: " +
mobile + "<br/>" +
"Gender: " +
gender + "<br/>" +
"Course: " +
course;
}
}
(10) RUN THE PROJECT:- Press F5, Browser opens automatically
(11) OUTPUT SCREENSHOTS :- Form View
(Before Submit):- You will see,
Name
Address
Age
Mobile fields
Gender (radio buttons)
Course (dropdown)
Submit (button)
(12) Output After
Clicking Submit:-
Example Output:-
Name: Ajay
Address: Bhagalpur
Age: 20
Mobile: 9832543210
Gender: Male
Course: BCA
Note:- Server
controls used
|
Control |
Purpose |
|
Label |
Display Text |
|
TextBox |
Takes Input Fields |
|
RadioButton |
Gender selection |
|
DropDownList |
Course selection |
|
Button |
Submit form |
ASP.NET CODE-BEHIND MODEL:-
The Code-Behind Model in ASP.NET is a programming approach
where the user interface (UI) and business logic (code) are kept in separate
files.
ASP.NET Supports Two Methods (Models):- In ASP.NET Web Forms,
there are two methods (models) used to write code:-
(1) SINGLE
FILE MODEL OR IN-LINE CODE
(2) MULTI-FILE
MODEL OR CODE-BEHIND
(1) SINGLE
FILE MODEL OR IN-LINE CODE:-
(Inline Code refers to the code that is written inside an
ASP.NET Web Page that has an extension of .aspx. It allows the code to be
written along with the HTML source code using a <Script> tag. Its major
point is that since it's physically in the .aspx file it's deployed with the
Web Form page whenever the Web Page is deployed.)
OR
(In-Line Code in ASP.NET is a method where C# code is written
directly inside the .aspx page using <script runat="server">
tags, instead of using a separate code-behind file. )
In-line code is code
that is embedded directly within the ASP.NET page.
This means:- UI (User Interface) (HTML + controls) and Logic
(C# code) , Both are written in the same file.
Why is it called “In-Line”?:- Because the code is written
“inside the page itself” (in-line with HTML) instead of being separated.
Syntax of In-Line Code:-
</>aspx
<script runat="server">
// C# code here
</script>
Explanation is:- runat="server" means:- Code will
run on the server, not in browser
The following code represents a sample
ASP.NET page that includes in-line code:-
</>aspx
<%@ Page Language="C#" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Inline
Code Example</title>
</head>
<body>
<form
runat="server">
Enter Name:
<asp:TextBox
ID="txtName" runat="server"></asp:TextBox>
<br
/><br />
<asp:Button ID="btnClick"
runat="server" Text="Submit"
OnClick="btnClick_Click" />
<br
/><br />
protected
void btnClick_Click(object sender, EventArgs e)
{
lblMsg.Text = "Hello " + txtName.Text;
}
</script>
</body>
</html>
Explanation of Example:-
<asp:TextBox> → User input
<asp:Button> → Calls event
<asp:Label> → Displays output
<script runat="server"> → Contains C# code
btnClick_Click() → Handles button click
When user clicks button → C# code runs → output shown
Real-Life Analogy:- Think like this:-
In-Line Code = Writing question &
answer on same page
Code-Behind = Question in one page,
answer in another
Advantages of IN-LINE CODE:-
Simple and fast, Less files, Good for small applications
Disadvantages of IN-LINE CODE:-
UI and logic mixed together, Difficult to manage large projects, Not
professional for big applications.
(2) MULTI-FILE
MODEL OR CODE-BEHIND or ( UNDERSTANDING THE CODE BEHIND THE PAGE) :-
Introduction :- In ASP.NET Web
Forms, every web page is divided into two main parts:
1. Frontend (ASPX Page):- Contains design/UI and Uses HTML +
ASP.NET controls
2. Backend (Code Behind – C#):- Contains logic / programming
and Written in C# (.aspx.cs file)
so This concept is called Code Behind Model
( Code Behind refers to the code for an ASP.NET Web page that
is written in a separate class file that can have the extension of .aspx.cs or
.aspx.vb depending on the language used. Here the code is compiled into a
separate class from which the .aspx file derives. You can write the code in a
separate .cs or .vb code file for each .aspx page. One major point of
Code-Behind is that the code for all the Web pages is compiled into a DLL file
that allows the web pages to be hosted free from any Inline Server Code. )
Code-behind refers to code for your ASP.NET page that is
contained within a separate class file. This allows a clean separation of your
HTML from your presentation logic.
The following sample illustrates an ASP.NET code-behind page:-
File Structure of Web Form of ASP.NET:-
|
File Name |
Purpose |
|
Default.aspx |
Design (User Interface) |
|
Default.aspx.cs |
Code Behind (Logic) |
|
Default.aspx.designer. cs |
Auto-generated control declarations |
How Code Behind is Connected to aspx:-
</>aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
Here some Important Points:- CodeFile → connects C# file and
Inherits → class name in code-behind
Complete Example:-
Step 1: ASPX Page (Design):-
</>aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>User
Form</title>
</head>
<body>
<form
id="form1" runat="server">
<div>
Enter Name:
<asp:TextBox
ID="txtName" runat="server"></asp:TextBox>
<br
/><br />
Enter Age:
<asp:TextBox ID="txtAge"
runat="server"></asp:TextBox>
<br
/><br />
<asp:Button ID="btnSubmit" runat="server"
Text="Submit" OnClick="btnSubmit_Click" />
<br
/><br />
<asp:Label ID="lblResult"
runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Step 2: Code Behind (This is code
behind which is written in c# file (C# File):-
</>c#
using System;
public partial class _Default : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
// Executes when
page loads
}
protected void
btnSubmit_Click(object sender, EventArgs e)
{
string name =
txtName.Text;
int age =
Convert.ToInt32(txtAge.Text);
lblResult.Text =
"Hello " + name + ", Your age is " + age;
}
}
Real-Life Analogy:- Think like
this:-
In-Line Code = Writing question
& answer on same page
Code-Behind = Question in one
page, answer in another
Advantages of code behind :-
Separation of UI and logic, Easy maintenance, Better for large projects, Clean
coding structure.
Disadvantages of code behind:-
More files to manage, Slightly difficult for beginners
DIFFERENCE BETWEEN CODE BEHIND AND IN
LINE CODE :-
|
Feature |
IN LINE |
CODE BEHIND |
|
Files Used |
One (.aspx) |
Two (.aspx +
.cs) |
|
Code Location |
Same file |
Separate file |
|
Maintainability |
Low |
High |
|
Usage |
Small apps |
Large apps |
PROPERTIES AND METHOD
IN ASP.NET OR C#:-
Properties:- Properties are members of a class
that provide a flexible mechanism to read, write, or compute the values of
private fields. They are a combination of methods that allow you to access and
update the value of a field in a controlled manner.
Defining Properties:- A property definition includes a get
accessor and/or a set accessor.
Syntax:-
accessModifier dataType PropertyName
{
get { // Return the
value of the field }
set { // Set the
value of the field }
}
Example:-
public class Person
{
private string name;
// Property to get and
set the name
public string Name
{
get { return
name; }
set { name =
value; }
}
}
Auto-Implemented
Properties:- For simple properties that do not require additional logic
in the accessors, you can use auto-implemented properties.
Example:-
public class Employee
{
// Auto-implemented
property
public int ID { get;
set; }
public string Name {
get; set; }
}
Read-Only Properties:- A
read-only property has only a get accessor and can only be assigned a value in the
constructor or directly in the property definition.
Example:-
public class Car
{
// Read-only
property
public string Model
{ get; }
public Car(string
model)
{
Model = model;
}
}
Computed Properties:-
Properties can also compute values dynamically based on other fields or
properties.
Example:-
public class Car
{
// Read-only
property
public string Model
{ get; }
public Car(string
model)
{
Model = model;
}
}
METHODS:- Methods
are blocks of code that perform a specific task. They can accept input
parameters, execute a sequence of statements, and optionally return a value.
Methods help in organizing and reusing code.
Defining Methods :- A method definition includes a return
type, a method name, a parameter list (optional), and a body enclosed in
braces.
Syntax:-
returnType MethodName(parameters)
{
// Method body
}
Example:-
public class Calculator
{
// Method to add two
numbers
public int Add(int
a, int b)
{
return a + b;
}
// Method to
multiply two numbers
public int
Multiply(int a, int b)
{
return a * b;
}
}
Calling Methods:- Methods
are called using the object of the class in which they are defined, or directly
if they are static.
Example:-
public class Program
{
public static void
Main(string[] args)
{
Calculator calc
= new Calculator();
int sum =
calc.Add(5, 3);
int product =
calc.Multiply(5, 3);
Console.WriteLine("Sum: " + sum);
Console.WriteLine("Product:
" + product);
}
}
Method Overloading:- Method
overloading allows you to define multiple methods with the same name but
different parameter lists. The compiler determines which method to call based
on the arguments passed.
Example:-
public class Printer
{
// Method to print
an integer
public void
Print(int number)
{
Console.WriteLine("Number: " + number);
}
// Method to print a
string
public void
Print(string message)
{
Console.WriteLine("Message: " + message);
}
}
Static Methods:- Static methods
belong to the class itself rather than an instance of the class. They are
called using the class name.
Example:-
public class MathUtilities
{
public static int
Square(int number)
{
return number *
number;
}
}
public class Program
{
public static void
Main(string[] args)
{
int square =
MathUtilities.Square(4);
Console.WriteLine("Square: " + square);
}
}
TYPES / NAMES OF CONTROLS IN ASP.NET /
USERS CONTROL IN C#:- A control method is simply a function (method)
that is used to control the behavior of a control (UI element) like a Button,
TextBox, Label, etc.
Basic Controls:-ASP.NET
provides three types of button control:-
(1) Button
: It displays text within a rectangular area.
Link Button : It displays text that looks like a hyperlink.
Image Button : It displays an image.
Common properties of the button
control:-
|
Property |
Description |
|
Text |
The text displayed
on the button. This is for button and link button controls only. |
|
ImageUrl |
For image button
control only. The image to be displayed for the button. |
|
AlternateText |
For image button
control only. The text to be displayed if the browser cannot display the
image. |
|
CausesValidation |
Determines whether
page validation occurs when a user clicks the button. The default is true. |
|
CommandName |
A string value that
is passed to the command event when a user clicks the button. |
|
CommandArgument |
A string value that
is passed to the command event when a user clicks the button. |
|
PostBackUrl |
The URL of the page
that is requested when the user clicks the button. |
(2) Text
Boxes and Labels:-
Text box controls are typically used to accept input from the
user. A text box control can accept one or more lines of text depending upon
the settings of the TextMode attribute.
Label controls provide an easy way to display text which can
be changed from one execution of a page to the next. If you want to display
text that does not change, you use the literal text.
|
Property |
Description |
|
TextMode |
Specifies the type
of text box. SingleLine creates a standard text box, MultiLIne creates a text
box that accepts more than one line of text and the Password causes the
characters that are entered to be masked. The default is SingleLine. |
|
Text |
The text content of
the text box. |
|
MaxLength |
The maximum number
of characters that can be entered into the text box. |
|
Wrap |
It determines
whether or not text wraps automatically for multi-line text box; default is
true. |
|
ReadOnly |
Determines whether
the user can change the text in the box; default is false, i.e., the user can
not change the text. |
|
Columns |
The width of the
text box in characters. The actual width is determined based on the font that
is used for the text entry. |
|
Rows |
The height of a
multi-line text box in lines. The default value is 0, means a single line
text box. |
3) Check
Boxes and Radio Buttons:- A check box displays a single option that the
user can either check or uncheck and radio buttons present a group of options from
which the user can select just one option.
To create a group of radio buttons, you specify the same name
for the GroupName attribute of each radio button in the group. If more than one
group is required in a single form, then specify a different group name for
each group.
If you want check box or radio button to be selected when the
form is initially displayed, set its Checked attribute to true. If the Checked
attribute is set to true for multiple radio buttons in a group, then only the
last one is considered as true.
|
Property |
Description |
|
Text |
The text displayed
next to the check box or radio button. |
|
Checked |
Specifies whether it
is selected or not, default is false. |
|
GroupName |
Name of the group
the control belongs to. |
(4) List
Controls:- ASP.NET provides the following controls
i.
Drop-down list,
ii.
List box,
iii.
Radio button list,
iv.
Check box list,
v.
Bulleted list.
|
Property |
Description |
|
Items |
The collection of
ListItem objects that represents the items in the control. This property
returns an object of type ListItemCollection. |
|
Rows |
Specifies the number
of items displayed in the box. If actual list contains more rows than
displayed then a scroll bar is added. |
|
SelectedIndex |
The index of the
currently selected item. If more than one item is selected, then the index of
the first selected item. If no item is selected, the value of this property
is -1. |
|
SelectedValue |
The value of the
currently selected item. If more than one item is selected, then the value of
the first selected item. If no item is selected, the value of this property
is an empty string (""). |
|
SelectionMode |
Indicates whether a
list box allows single selections or multiple selections. |
|
Property |
Description |
|
Text |
The text displayed
for the item. |
|
Selected |
Indicates whether
the item is selected. |
|
Value |
A string value
associated with the item. |
(5) HyperLink Control:- The
HyperLink control is like the HTML <a> element.
Basic syntax for a hyperlink control:-
|
Property |
Description |
|
ImageUrl |
Path of the image to
be displayed by the control. |
|
NavigateUrl |
Target link URL. |
|
Text |
The text to be
displayed as the link. |
|
Target |
The window or frame
which loads the linked page. |
(6) Image
Control:- The image control is used for displaying images on the web page,
or some alternative text, if the image is not available.
|
Property |
Description |
|
AlternateText |
Alternate text to be
displayed in absence of the image. |
|
ImageAlign |
Alignment options
for the control. |
|
ImageUrl |
Path of the image to
be displayed by the control. |
EXPOSING USER CONTROL PROPERTIES AND
METHODS:-
Meaning of “Exposing” in C#:-
Simple Definition:- Exposing means making something accessible (available) to
other classes, pages, or users. In C# (especially ASP.NET), When we say
“exposing properties and methods”, it means, Making variables (properties) and
functions (methods) of a control accessible from outside, such as from a web
page or another class. OR in C# “Exposing” means making internal members (data
or functions) accessible to the outside world in a controlled way.
Example (Simple Concept):-
public string Name { get; set; } // public = exposed
(accessible outside), private = not exposed (hidden)
So, Exposing = using access modifiers like public to allow
access (Meaning of get and set:- get → Read value (Access the
value, set → Assign value (Assign the
value to a variable)
Example Without Exposing (Problem)
</> c#
string message = "Hello";
This is private by default, so, Other pages cannot access it
Example With Exposing (Solution):- public
string Message { get; set; }
Now:- Other pages can access it, So, Exposing = using access
modifiers (mainly public) to allow controlled access
TYPES OF EXPOSING:- There are 3 main types.
TYPE 1: Exposing Properties:-Meaning:- Making data (variables)
accessible using public properties.
FULL EXAMPLE:- User Control
User Interface) UI (MyControl.ascx)
</>asp
<asp:Label ID="lblName"
runat="server"></asp:Label>
Code Behind (MyControl.ascx.cs)
</>c#
public partial class MyControl : System.Web.UI.UserControl
{
public string
NameText
{
get
{
return
lblName.Text;
}
set
{
lblName.Text
= value;
}
}
}
Main Page (Default.aspx.cs):-
</>C#
protected void Page_Load(object sender, EventArgs e)
{
MyControl1.NameText
= "Ajay Kumar";
}
OUTPUT:-Label shows: Ajay Kumar
TYPE 2: Exposing
Methods:- Meaning:- Making functions
accessible using public.
FULL EXAMPLE:- In
User Control
</>C#
FULL EXAMPLE:- In
User Control
public void
DisplayMessage(string msg)
{
lblName.Text = msg;
}
In Web Page
</>C#
protected void Page_Load(object
sender, EventArgs e)
{
MyControl1.DisplayMessage("Welcome
Ajay!");
}
OUTPUT:- Label shows: Welcome
Ajay!
EXAMPLE OF FULL
WORKING PROGRAM of Exposing User Control Properties and Methods in ASP.NET (C#) with:-
Example Goal:- We will create:-
A User Control that shows a message, The Main Page will,
Set message using Property, Change
message using Method
(1) Create User Control (MyControl.ascx):- Design User Interface (UI)
</>asp
<%@ Control
Language="C#" AutoEventWireup="true"
CodeFile="MyControl.ascx.cs" Inherits="MyControl" %>
<asp:Label
ID="lblMessage" runat="server" Text="Default
Message"></asp:Label>
<br />
<asp:Button
ID="btnChange" runat="server" Text="Click Me"
OnClick="btnChange_Click" />
(2) Code Behind (MyControl.ascx.cs):-
</>c#
using System;
public partial class MyControl
: System.Web.UI.UserControl
{
// Exposing Property
public string Message
{
get { return lblMessage.Text; }
set { lblMessage.Text = value; }
}
// Exposing Method
public void ShowMessage(string msg)
{
lblMessage.Text = msg;
}
// Internal button event
protected void btnChange_Click(object
sender, EventArgs e)
{
lblMessage.Text = "Message changed
inside User Control!";
}
}
(3) Register User Control in Main Page
(Default.aspx):-
</>asp
<%@ Register
Src="~/MyControl.ascx" TagPrefix="uc" TagName="MyControl"
%>
<!DOCTYPE html>
<html>
<head
runat="server">
<title>User Control
Example</title>
</head>
<body>
<form id="form1"
runat="server">
<uc:MyControl
ID="MyControl1" runat="server" />
<br /><br />
<asp:Button ID="btnSet"
runat="server" Text="Set Property"
OnClick="btnSet_Click" />
<asp:Button ID="btnMethod"
runat="server" Text="Call Method"
OnClick="btnMethod_Click" />
</form>
</body>
</html>
(4) Code Behind (Default.aspx.cs):-
</>c#
using System;
public partial class Default :
System.Web.UI.Page
{
protected void btnSet_Click(object sender,
EventArgs e)
{
// Using Property
MyControl1.Message = "Hello Ajay
(From Property)";
}
protected void btnMethod_Click(object sender,
EventArgs e)
{
// Using Method
MyControl1.ShowMessage("Hello Ajay
(From Method)");
}
}
OUTPUT EXPLANATION:-
Initial Output, Shows:-
Label → “Default Message”
Button → “Click Me”
Two buttons → Set Property,
Call Method
After Clicking “Set
Property”:- Output:-Hello Ajay (From
Property), Property is used
After Clicking “Call
Method”:- Output:- Hello Ajay (From
Method), Method is used
Final Exam Definition:-
Exposing user control properties and
methods in C# means making the internal data and functions of a user control
accessible to the parent page using public members, so that the page can
interact with and control the behavior of the user control.
ASP.NET CONTROLS:-
VALIDATION :- The validation control is used to
implement page level validity of data entered in the server controls. This
check is done before the page is posted back ( POSTBACK Means the data cannot upload to the server until the client
validation is executed successfully) to the server,
thus avoid a round trip to the server. If the data does not pass
validation, it will display an error message to the user. It is an important
part of any web application.
The Validation controls are used for validating the data entered in
Text Box(input) controls. When any user enters the data on a text Box (web page) and
submits the page on the server ,then validation controls are used to check the data field entered
by the user .if any data entered by the user is invalid (not correct format) then
validation control displays an error
message on the screen. All the error
message is defined as properties values of validation controls. All the
validation controls comes
under System.UI.Webcontrols Namespace.
There
are two types of validation:-
1. Client side validation.
2. Server side validation.
(1) CLIENT
SIDE VALIDATION :- Client-side validation makes the
process fast as there is less number of hits to the server. It is good but we
have to be dependent on browser and scripting language support. The main
advantage is that it prevents a page from being POSTBACK to the server until
the client validation is executed successfully. Client-side
validation is a great convenience for users. It saves time they would otherwise
spend waiting for a round trip to the server that might return validation
errors. ASP.NET validation controls provide functionality to perform validation
using client script. By default, when client-side validation is being
performed, the user cannot post the page to the server if there are errors on
the page thus the user experience with the page is enhanced.
Client-side objects:- Page_IsValid
Boolean variable, Indicates whether the page is currently valid. The validation
scripts keep this up to date at all times.
Page_ValidationActive Boolean variable:- Indicates
whether validation should take place. Set this variable to False to turn off
validation programmatically.
Isvalid:- Boolean property, This is a property on each client validator
indicating whether it is currently valid.
Page_ValidationSummaries Array of elements:- This
is an array containing all of the validation summaries on the page.
Client-Side APIs:- ValidatorValidate(val), Takes a
client-validator as input. Makes the validator check its input and update its
display.
ValidatorEnable(val, enable):- Takes a
client-validator and a Boolean value. Enables or disables a client validator.
Being disabled will stop it from evaluating and it will always appear valid.
ValidatorHookupControl(control, val):- Takes
an input HTML element and a client-validator. Modifies or creates the element’s
change event so that it updates the validator when changed. This can be useful
for custom validators that depend on multiple input values.
Page_ClientValidate(val):- Takes validation group
as input and validate all validators of the group and returns bool.
(2) SERVER SIDE VALIDATION:-
Server-side validation is used to remove the limitation of client browsers
dependencies and scripting language support. In
the Server Side Validation We can use ASP.NET validation , which will ensure
client , and server validation. It work on both end, first it will work on
client validation and then on server validation. In the Server Side Validation,
the input submitted by the user is being sent to the server and validated using
one of server side scripting languages such as ASP.Net, PHP etc. After the
validation process on the Server Side, the feedback is sent back to the client
by a new dynamically generated web page.
Server
side validation for asp.net textbox, dropdownlist, checkboxlist,
radiobuttonlist, listbox, checkbox and radiobutton controls
THERE ARE SOME IMPORTANT VALIDATION CONTROLS THAT ARE USED IN
ASP.NET. WHICH ARE GIVEN BELOW :-
(1) The RequiredField
Validator control
(2) The RangeValidator control
(3) The
RegularExpressionValidator control
(4) The CompareValidator
control
(5) The customValidator
control
(6) The Validationsummary
control
(1) The RequiredField
Validator control ;- The RequiredFieldValidator control is
used to make an input control as a mandatory field or the input field should
not be empty. The other validation controls do not validate for an empty field.
They validate, when user enter the data.
For
example, :- you can specify that users must fill password in a password TextBox
before submit the login form., You have to set two important properties when
using the RequiredFieldValdiator control.
Properties :- ControlToValidate: The ID of the
control for which RequiredFieldValidator control will be associated.
ErrorMessage:- This property is used to show the error
message, if the user forget to enter the data, then custom error message will
appear.
You
have to set the above two given property in all the ASP.NET validation control.
These two properties are common to all validation control except
ValidationSummary control.
Example:-
<asp:TextBox
ID="txtName" runat="server" Width="200px">
</asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtName"
ErrorMessage="Enter Name" ForeColor="Red">
</asp:RequiredFieldValidator>
Others properties of RequiredField Validator control
|
Property |
Description |
|
AccessKey |
It
is used to set keyboard shortcut for the control. |
|
BackColor |
It
is used to set background color of the control. |
|
BorderColor |
It
is used to set border color of the control. |
|
Font |
It
is used to set font for the control text. |
|
ForeColor |
It
is used to set color of the control text. |
|
Height |
It
is used to set height of the control. |
|
Width |
It
is used to set width of the control. |
(2) The RangeValidator control
:- It
confirms that user input data is within a specified range of values. The input
value should come between a certain minimum and maximum value otherwise it will
give error.
Set
the Type property according to input data while using the RangeValidator
control. By default, the Type property has the value String. If you want to
specify the range of date of birth, then set Type as Date. Along with
ControlToValidate and ErrorMessage you have to set the following property of
RangeValidator control.
Important Properties:-
MinimumValue: The
minimum value of the validation range. MaximumValue: The maximum value of the
validation range.
Type : (
Type means which type of values you want to entered in the textbox) Possible
values are String, Integer, Double, Date, and Currency.
Some Others properties :- Example
<asp:TextBox
ID="txtAge" runat="server" Width="90px">
</asp:TextBox>
<asp:RangeValidator
ID="RangeValidator1" runat="server"
ForeColor="Red" ControlToValidate="txtAge"
ErrorMessage="Enter age between 18 to 60" MaximumValue="60"
MinimumValue="18" Type="Integer">
</asp:RangeValidator>
|
Property |
Description |
|
AccessKey |
It
is used to set keyboard shortcut for the control. |
|
BackColor |
It
is used to set background color of the control. |
|
BorderColor |
It
is used to set border color of the control. |
|
Font |
It
is used to set font for the control text. |
|
ForeColor |
It
is used to set color of the control text. |
|
Height |
It
is used to set height of the control. |
|
Width |
It
is used to set width of the control. |
|
ToolTip |
It
displays the text when mouse is over the control. |
|
MinimumValue |
The
minimum value of the validation range. |
|
MaximumValue |
The
maximum value of the validation range. |
(3) The
RegularExpressionValidator control :- The RegularExpressionValidator control
performs its validation according to the regular expression. You can check the
predefined pattern, such as a phone number, postal code, e- mail address,
dates, and so on. The control uses the ValidationExpression property to set a
valid regular expression that is applied to the input data.
RegularExpression
Properties:-
|
Property |
Description |
|
AccessKey |
It
is used to set keyboard shortcut for the control. |
|
BackColor |
It
is used to set background color of the control. |
|
BorderColor |
It
is used to set border color of the control. |
|
Font |
It
is used to set font for the control text. |
|
ForeColor |
It
is used to set color of the control text. |
|
Height |
It
is used to set height of the control. |
|
Width |
It
is used to set width of the control. |
|
ToolTip |
It
displays the text when mouse is over the control. |
|
ErrorMessage |
It
is used to set error message that display when validation fails. |
|
ControlToValidate |
It
takes ID of control to validate. |
|
ValidationExpression |
It
is used to set regular expression to determine validity. |
Example
<asp:TextBox
ID="txtEmailID" runat="server" Width="200px">
</asp:TextBox>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server"
ForeColor="Red"
ControlToValidate="txtEmailID" ErrorMessage="Enter correct
EmailID"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
NOTE :-( ValidationExpression="\w+([-+.']\w+)*@\w+([-
.]\w+)*\.\w+([-.]\w+)*"> )
It
is use to check whether or not the text matches a certain pattern. There are
some elements that used to make expression, which are given below:-
\d
--> [0->9] .it takes value zero to nine.
\D-->
Other than [0->9].
\w
--> [a->z][A->Z][0->9]
\s
--> space
\S-->
other value except space.
{Length}-->{min
,max}
[
] --> choice of given character(one out of them).
(
) --> group of validator
|
--> OR
We
can use special characters which are given below:
*
--> 0 -> more numeric values
+
--> 1 --> more numeric values
?
--> 0(min) or 1 (max)
(4) The CompareValidator
control :- CompareValidator
control is used to perform three different types of validation tasks.
(1) To perform a data type check.
(2) To compare the value entered into a form field
against a given fixed value.
(3) To compare the value of one form field against
another field.
|
Property |
Description |
|
AccessKey |
It
is used to set keyboard shortcut for the control. |
|
BackColor |
It
is used to set background color of the control. |
|
BorderColor |
It
is used to set border color of the control. |
|
Font |
It
is used to set font for the control text. |
|
ForeColor |
It
is used to set color of the control text. |
|
Height |
It
is used to set height of the control. |
|
Width |
It
is used to set width of the control. |
|
ToolTip |
It
displays the text when mouse is over the control. |
|
ErrorMessage |
It
is used to set error message that display when validation fails. |
|
ControlToCompare |
It
takes ID of control to compare with. |
|
ControlToValidate |
It
takes ID of control to validate. |
|
Operator |
Given
values are DataTypeCheck, Equal, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual
and NotEqual.. |
|
Type: |
The
type of value for comparison. Given values are String,
Integer, Double, Date, and Currency. |
Example:-
<asp:TextBox
D="txtConPassword" runat="server"
Width="164px"
TextMode="Password">
</asp:TextBox>
<asp:CompareValidator
ID="CompareValidator1" runat="server"
ForeColor="Red"
ControlToCompare="txtPassword"
ControlToValidate="txtConPassword" ErrorMessage="Re-Enter Password">
</asp:CompareValidator>
(5) The customValidator
control :- (customValidator control means write your
method to perform extra validation )
ASP.NET
provides different types of inbuilt validation controls, which provides number
of validation facilities. In many situations these inbuilt validation controls
does not work and you want custom validation control.
CustomValidator
control enables you to create your own validation and that validation can run
with the other validation control on the page. The CustomValidator control
performs validation, based upon your code, you write. You can write validation
code that will be executed on the client side using JavaScript,or with
server-side validation.
The
CustomValidator control can work client-side, server-side, or both.
Drag
the CustomValidator control on the web page. Set the ControlToValidate and
ErrorMessage property. Double click on the CustomValidator control; you will
get the event handler as: protected void CustomValidator1_ServerValidate(object
source, ServerValidateEventArgs args )
{
}
Suppose that a
user wants the input validation with following criteria.
(A) Password must be between 6-12 characters.
(B) Must have one capital letter.
(C ) Must have one lowercase letter.
(D) Must have one numeric value.
NOTE : NO MORE
PROPERTIES IN CUSTOMVALIDATOR,
Write your
custom logic in the given event handler as given below.
Example:-
using System;
using
System.Web.UI.WebControls;
public partial
class CustomValidation : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
}
protected void
CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args )
{
string inputData
= args.Value; args.IsValid = false;
if
(inputData.Length < 6 || inputData.Length > 12) return;
bool upperCase =
false; foreach (char ch in inputData)
{
if (ch >= 'A'
&& ch <= 'Z')
{
upperCase =
true; break;
}
}
if (!upperCase)
return; bool lowerCase = false;
foreach (char ch
in inputData)
{
if (ch >= 'a'
&& ch <= 'z')
{
lowerCase =
true; break;
}
}
if (!lowerCase)
return; bool number = false;
foreach (char ch
in inputData)
{
if (ch >= '0'
&& ch <= '9')
{
number = true;
break;
}
}
if (!number)
return; args.IsValid = true;
}
}
(6) The Validationsummary
control :- This
control summarizes the error messages from all validation controls on a Web
page in a single location.
ValidationSummary
control is useful when working with large forms.
If
a user enters the wrong value in the field located at the end of the page, then
the user might never see the error message. ValidationSummary control can
displays a list of errors at the top of the form. It does not support
ErrorMessage and ControlToValidate property. It automatically displays the
error message in the form of MessageBox or summary if error occurs due to empty
input field or wrong data.
Important
Propertie :-
DisplayMode:-
BulletList, List, and SingleParagraph
HeaderText:-
Display header text above the validation
summary.
ShowMessageBox:
It is used to display a popup alert box
ShowSummary: It
hides the validation summary in the page.
By default
ShowMessageBox property value is set False and ShowSummary property value is
set True. You can use these properties according to your need.
Example:
In
the given example, We have not entered EmpID and EmpName and entered some wrong
data(Email, password), so you can see the error messages.
Example:-
<asp:ValidationSummary
ID="ValidationSummary1" runat="server" >
</asp:ValidationSummary>
SOME OTHERS PROPERTIES:-
|
Property |
Description |
|
AccessKey |
It is used to
set keyboard shortcut for the control. |
|
BackColor |
It is used to
set background color of the control. |
|
BorderColor |
It is used to
set border color of the control. |
|
Font |
It is used to
set font for the control text. |
|
ForeColor |
It is used to
set color of the control text. |
|
Height |
It is used to
set height of the control. |
|
Width |
It is used to
set width of the control. |
|
ToolTip |
It displays
the text when mouse is over the control. |
|
ShowMessageBox |
It displays a
message box on error in up- level browsers. |
|
ShowSummary |
It is used to
show summary text on the form page. |
|
ShowValidationErrors |
It is used to
set whether the validation summary should be shown or not. |
BaseValidator
Class :- The validation control classes are
inherited from the BaseValidator class hence they inherit its properties and
methods. Therefore, it would help to take a look at the properties and the
methods of this base class, which are common for all the validation controls:-
BaseValidator Class Members OR Properties are:-
|
Members |
Description |
|
ControlToValidate |
Indicates
the input control to validate. |
|
Display |
Indicates
how the error message is shown. |
|
EnableClientScript |
Indicates
whether client side validation will take. |
|
ErrorMessage |
Indicates
error string. |
|
Text |
Error
text to be shown if validation fails. |
|
IsValid |
Indicates
whether the value of the control is valid. |
|
SetFocusOnError |
It
indicates whether in case of an invalid control, the focus should switch to
the related input control. |
|
ValidationGroup |
The
logical group of multiple validators, where this control belongs. |
|
Validate() |
This
method revalidates the control and updates the IsValid property. |
RICH CONTROLS :-
In addition to
the preceding controls, the ASP.NET page framework provides a few,
task-specific controls called rich controls. Rich controls are built with
multiple HTML elements and contain rich functionality.
Examples of rich
controls are the Calendar control and the AdRotator control, FileUpload etc.
(1) THE CALENDAR CONTROL:- ASP.NET provides a Calendar control that
is used to display a calendar on a Web page. ASP.NET Calendar control displays
a month calendar that allows user to select dates and move to the next and
previous months.
By default, this
control displays the name of the current month, day headings for the days of
the weeks, days of the month and arrow characters for navigation to the
previous or next month.
The class
hierarchy for this control is as follows: Object -> Control -> WebControl
-> Calendar
The Calendar is
complex, powerful Web server control that you can use to add a calendar feature
to your web page. We can use Calendar control to display any date between 0
A.D. and 9999 A.D.
Properties
and Events of the Calendar Control:-
|
Properties |
Description |
|
Caption |
Gets or sets
the caption for the calendar control. |
|
CaptionAlign |
Gets or sets
the alignment for the caption. |
|
CellPadding |
Gets or sets
the number of spaces between the data and the cell border. |
|
CellSpacing |
Gets or sets
the space between cells. |
|
DayHeaderStyle |
Gets the style
properties for the section that displays the day of the week. |
|
DayNameFormat |
Gets or sets
format of days of the week. |
|
DayStyle |
Gets the style
properties for the days in the displayed month. |
|
FirstDayOfWeek |
Gets or sets
the day of week to display in the first column. |
|
NextMonthText |
Gets or sets
the text for next month navigation control. The default value is >. |
|
NextPrevFormat |
Gets or sets
the format of the next and previous month navigation control. |
|
OtherMonthDayStyle |
Gets the style
properties for the days on the Calendar control that are not in the displayed
month. |
|
SelectedDate |
Gets or sets
the selected date. |
|
TodaysDate |
Gets or sets
the value for today's date. |
|
Events |
Description |
|
SelectionChanged |
It
is raised when a day, a week or an entire month is selected. |
|
DayRender |
It
is raised when each data cell of the calendar control is rendered. |
|
VisibleMonthChanged |
It
is raised when user changes a month. |
This is the code of date format
public partial
class _Default : System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
Label1.Text =
Calendar1.SelectedDate.ToLongDateString();
Label2.Text =
Calendar1.SelectedDate.ToShortDateString();
Label3.Text =
Calendar1.TodaysDate.ToLongDateString();
Label4.Text =
(Calendar1.TodaysDate - Calendar1.SelectedDate).Days.ToString();
}
}
(2) THE ADROTATOR :- (The AdRotator
control will support only XML file during program execution) AdRotator is a
Rich Web Control in ASP.NET. AdRotator control is used to make rotating
advertisement in ASP.NET.It displays the different different images in web page
when you refresh the web page. You can provide the information about the images
which is displayed in AdRotator using XML file or database. When we click on
the images it will redirect on NavigateUrl.
The following
are the AdRotator class properties control.
(1) AdvertisementFile:
The path of the XML file in which you store the information of images.
(2) AlternateTextField:- A data field to use
instead of the Alt text for an advertisement.
(3) ImageUrlField:- The name of the image
url field in which image path is store.
(4) NavigateUrlField:- The name of the
navigate url field in which navigate url is store.
(5) Target:
The target property specify frame that display the content of the AdRotator. It
has four type _blank, _parent, _self, _top.
(6) DataSourceID:-This
property overrides BaseDataBoundControl.DataSourceID and returns or sets the ID
of the control from which the data-bound control retrieves its list of data
items.
(7) DataSource :- This property gets or sets
the object from which the data-bound control retrieves its list of data items.
Its default value is a null reference (Nothing in VB.NET). When Web developers
set the property, the ValidateDataSource method is called. In addition, if the
data-bound control has already been initialized, the OnDataPropertyChanged
method is called to set the RequiresDataBinding property to true. This property
cannot be set by themes or style sheet themes.
(8) Font :- Software developer can use this
property to specify the font properties of the Web Server control. This
property includes subproperties that can be accessed declaratively in the form
of Property-Subproperty (for example Font-Bold) or programmatically in the form
of Property.Subproperty (for example Font.Bold).
|
Method |
Description |
Example |
|
GetAdvertisement |
Returns
HTML that displays the advertisement in the page |
<%
set adrot=Server.CreateObject("MSWC.AdRo tator")Response.Write(adrot.GetAdvertisement( "ads.txt"))%> |
HOW TO
INSERT ADROTATOR CONTROL EXAMPLE IN ASP.NET STEPS :-
Step 1 – Open
the Visual Studio –> Create a new empty Web application.
Step 2 – Create
a New web page for display AdRotator control.
step 3 – Drag
and drop AdRotator Control on web page from toolbox.
step 4 – go to
Add New Item –> Add New XML File in project for write advertisement detail.
step 5 – Assign
XML File to AdvertisementFile Property of AdRotator control.
The XML file
code (AdXML.xml) is as: (Because The AdRotator control will support only XML
code)
<?xml
version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>~/Images/image1.gif</ImageUrl>
<NavigateUrl>http://roseindia.net</NavigateUrl>
<AlternateText>Roseindia</AlternateText>
<Keyword>Site1</Keyword>
</Ad>
AdRotator.aspx
(source page):
<%@
Page Language="C#" AutoEventWireup="true"
MasterPageFile="~/RoseindiaMaster.master"
CodeFile="AdRotator.aspx.cs" Inherits="AdRotator" %>
<asp:Content
ID="Content1" runat="server"
contentplaceholderid="ContentPlaceHolder1">
<div>
<h2
style="color:Green">AdRotator in ASP.NET 4, C#</h2>
<asp:AdRotator
ID="AdRotator1" runat="server"
Width="468px"
Height="60px"
AdvertisementFile="~/XML/Adxml.xml"/>
</div>
</asp:Content>
WHAT IS ADVERTISEMENT FILE PROPERTY IN ADROTATOR CONTROL :-
Use the
AdvertisementFile property to specify the location of an XML file that contains
advertisement information. The XML file must reside within the same Web site.
For deployment and security purposes, it is strongly recommended that you place
the file in the same Web application. It is only possible to access an XML file
that is located in a different application on the same site if the application
has sufficient trust.
You can set this
property to either an absolute path or a path relative to the XML file. Use a
relative path to simplify deployment. If you use a relative path, that path is
relative to the location of the page or user control that contains the
AdRotator control.
The AdvertisementFile
property is optional. An advertisement can also be programmatically set in the
AdCreated event.
The XML file
contains the following predefined attributes. Only
the ImageUrl
attribute is required. OR Advertisement File Elements which are required during
web development and AdRotator use.
|
Attribute |
Description |
|
ImageUrl |
The URL of the
image to display. |
|
Height |
The height of
the image, in pixels (optional). |
|
Width |
The width of
the image, in pixels (optional). |
|
NavigateUrl |
The URL of the
page to navigate to when the AdRotator control is
clicked. |
|
AlternateText |
The text to
display if the image is unavailable. On some browsers, this text is displayed
as a ToolTip. |
|
Keyword |
The category
for the advertisement. This is used by the AdRotator control to filter the
list of advertisements for a specific category. |
|
Impressions |
A value that
indicates how often an advertisement is displayed in relation to other
advertisements in the XML file. |
FileUpload:-
The
FileUpload control is a simple and straightforward control yet considered to be
among the rich controls. As the name suggests, its purpose is to upload files
and it easily resolves the problem to retrieve data from the user’s computer by
using a programming language that executes entirely on the server. The
FileUpload is declared like this:
<asp:FileUpload
ID="MyUpload" runat="server" />
When inspecting
the result on the browser, you can find out that this control generates the
well known “<input type=”file”>” HTML tag. Since this tag doesn’t provide
almost any customisation options, the FileUpload control isn’t quite
customisable either. Generally, it represents a rectangular box containing a
button-like graphic inside. When clicked on, this control opens a dialogue
window to browse for files from. Once a file is chosen, it is displayed on the
FileUpload control. However, this doesn’t mean the file is uploaded. It’s just
readied and is uploaded later, when the page is posted back.
As mentioned
above, the FileUpload is not especially customisable. There are, however, a few
commonly used solutions to add some more functionality to the uploader.
A couple of
examples:- Allowing multiple files to be uploaded at once by using the
AllowMultiple property:-
<asp:FileUpload
ID="MyUpload" AllowMultiple="true" runat="server"
/>
Modifying the
uploaded file size limit: by default this limit is set to 4MB. Unlike the above
example, this functionality can be altered through the config file by
specifying a value for the maxRequestLength setting in the httpRuntime tag. In
the following example files up to 16384 bytes (16MB) are allowed:
<?xml
version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<!-- Other
settings omitted for clarity. -->
<httpRuntime
maxRequestLength="16384" executionTimeout="3600"/>
</system.web>
</configuration>
ExecutionTimeout
is commonly used alongside maxRequestLength and it restricts the time in
seconds for a file request to be executed. While extremely useful in some
scenarios, maxRequestLength shouldn’t be used when not needed because
abnormally large files can temporarily block the ASP .NET threads and even be
part of Denial of Service
(DoS) attacks.
A PROGRAM FOR SIMPLE VALIDATION USING ALL VALIDATOR EXAMPLE :-
(1) Question :- Make a web form
in ASP.NET using all Validator, Which will take Input from the user and
validate all the entered record also check password and e mail id, and display
appropriate message if entered information are wrong.
Answer
step by step :-
1 Step : Start → Visual studio → project → c# →web
→ ASP.NET web
application or ASP.NET empty web application → file name →set location → ok
2 step: - After click , You see right
side of the screen and there is a option Solution explorer and just below the
web file name(ajayWeb) which is create by you, Now select that file name
(ajayWeb) and click right button of the mouse →Add→New Item → visual c# → web
form → here give the file (like validatorCheck) → Add (After click Add you will
get some code of HTML)
(THIS
IS AUTOMATIC GENERATED CODE BY SYSTEM )
<%@
Page Language="C#" AutoEventWireup="true"
CodeBehind="velaiNew1.aspx.cs" Inherits="WebApplication4.velaiNew1"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml" >
<head
runat="server">
<title>Untitled
Page</title>
</head>
<body>
<form
id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Just below the there is a option DESIGN,
Now click on Design tab
After
click design tab you will get like this screen
NOW
3 STEP :- Table (Menu) →
Insert table → Row, Columns
( Select
rows and columns as per your requirement) Her I will take rows=5 and columns=3
→ ok
4 step :- ToolBox→ Label (Now drag and
drop five (5) labels in your table, in 1st row label1, 2nd row label2, 3rd row
label3, 4th row label4, 5th row label5, and Change the Text of all labels in
proprieties of label like label1 = ENTER USER NAME, label2 = ENTER USER AGE,
etc.)
5TH STEP :-
Button (Drag and drop on the web form just)
6TH STEP :-
ToolBox → TextBox (Drag and drop textbox in front of the labels like in front
of label1=TextBox1, label2=TextBox2, label3=TextBox3, label4=TextBox4,
label5=TextBox5.
(THIS
IS THE FIGURE THE SCREEN SHOT OF LABELS AND TEXT CHANGE WITH TEXTBOX )
7 STEP :- Now keep mouse
pointer in the 3rd column of the table which kept on the web form.
(NOTE :- NOW I AM USING The RequiredField Validator control by
this control user con not leave the Empty any TextBox )
8 STEP:- ToolBox → Validation →
RequiredField Validator (Double click on the RequiredFieldValidator or Drag and
drop in the table, like TextBox1= RequiredFieldValidator, TextBox2=
RequiredFieldValidator, TextBox3= RequiredFieldValidator, TextBox4=
RequiredFieldValidator, TextBox5= RequiredFieldValidator,).
9 STEP :- Select RequiredFieldValidator of
the TextBox1 and go to properties of RequiredFieldValidator in ErrorMessage
option and put the message Like ErrorMessage = ENTER USER NAME, and Properties
ControlToValidate=TextBox1
Now do the same
thing in all the ErrorMessage like TextBox2=ENTER USER AGE, and Properties
ControlToValidate=TextBox2, TextBox3=ENTER USER E MAIL ID, and Properties
ControlToValidate=TextBox3,
TextBox4=ENTER
PASSWORD, and Properties ControlToValidate=TextBox4, TextBox5=ENTER CONFIRM
PASSWORD, and Properties ControlToValidate=TextBox5 )
(THIS IS THE FIGURE THE SCREEN SHOT OF
RequiredField
Validator control WITH ALL TEXTBOX )
(NOTE
:- NOW I AM USING:- The CompareValidator
control, By this control we can compare of two control like password and
confirm password)
10 STEP:- Now again keep
the mouse pointer, near the TextBox5 RequiredField Validator control for
confirm checking,
11 STEP:- ToolBox →
Validation → CompareValidator (Double click on control) after double click on
control select the CompareValidator and go to properties ErrorMessage (option)=
confirm Password is not matching,
Proporties
ControlToValidate = TextBox5, Proporties ControlToCompare=TextBox4 (Because we
will compare password(TextBox4) and confirm password (TextBox5)
(THIS
IS THE FIGURE THE SCREEN SHOT OF
CompareValidator
WITH TEXTBOX4, TEXTBOX5 )
12 STEP:- Now again keep
the mouse pointer, near the TextBox2 RequiredField Validator control for range
checking minimum and maximum
13 STEP:- ToolBox →
Validation → RangeValidator (Double click on control) after double click on
control select the RangeValidator and go to properties ErrorMessage (option)=
ENTER AGE BETWEEN 18 TO 30 , Proporties ControlToValidate = TextBox2,
Proporties MinimamValue=18, Proporties MaximamValue=30, Proporties Type=Integer
)
(NOTE :- NOW I AM USING The RegularExpressionValidator control , By
this control we can check entered E Mail ID is Valid or Not )
14 STEP:- Now again keep
the mouse pointer, near the TextBox3 RequiredField Validator control for E Mail
ID checking
15 STEP:- ToolBox →
Validation → RegularExpressionValidator (Double click on control) after double
click on control select the RegularExpressionValidator and go to properties
ErrorMessage (option)= ENTER VALID E MAIL ID , Proporties ControlToValidate =
TextBox3, Proporties ValidationExpression= Internet e mail address )
(THIS
IS THE FIGURE THE SCREEN SHOT OF
(NOTE :- NOW I AM USING The Validationsummary control , By this
control we can summaries all the Error Message at a place which is write by the
programmer )
16 STEP:- Now again keep
the mouse pointer anywhere on the web form.
17 STEP:- ToolBox →
Validation → Validationsummary control (Double click on control)
(THIS
IS THE FIGURE THE SCREEN SHOT OF Validationsummary )
(NOTE :- NOW I AM USING The customValidator control ,
customValidator control is use only manually during the code writing by the
programmer )
NOW RUN THE FILE
(2) Question: - Make a
web page to display the advertisement random during internet web site executing
using The AdRotator control in ASP.NET.
Answer :-
1 Step:- Start → Visual
studio → File → new → project → visual c# → web → ASP.NET → web application
form → File name (webABC) → ok
After
ok you will get like this screen
Now
see right side of the screen there is solution webabc(file name), and just
below WEBABC(File name)
2 step :- select WEBABC
file from solution explorer and right click of the mouse and select Add →New
Item → visual c# → web form → then give file name OR leave it → ADD
3 step :- Go to Deign Tab
(Just below, WEB FORM1) → Toolbox→Label (properties Text= MADE BY AJAY KUAMR
PATHAK)
ALSO
TYPE DIRECTLY ON THE WEB PAGE TO DISPLAY RANDOMLY ADVERTISEMENTS USING
ADROTATOR IN ASP.NET )
4 STEP :- Table (Menu) → Insert table (Select rows=2, columns =1) → ok (Now expend the table size)
5 step:- ToolBox → label
(properties Text = Sponsored Advertisement)
5
step :- ToolBox → AdRotator (Drag and drop on the web form
6 STEP :- (Now we will
work in XML file because AdRotator control executive in XML file)
Now
see right , there is solution explorer, just below WEBABC (file name) selct
webabc right click of the mouse on webabc and → Add →New Item →visual C# → XML
file → now give file name like (ADVERTISEMENTS_XMLFile1.xml) → Add.
After
add XML file the screen will look like
(7) step :- Now go to web
form, then go to solution explorer→ WEBABC file → right click mouse select Add
→ New Folder (change name folder name like JPEG FILE NAME) →Now select JPEG
folder
→ Add → Existing Item → Now select here folder name where you have stored the
jpeg file for advertisement , select file and click → Add (after click add all
jpeg file will store in New folder where we created like JPGE folder, now all
file will display in the folder)
(8) step: - Now go to web
file where all XML code is displaying → write code of XML for adding the jpeg
file
<?xml
version="1.0" encoding="utf-8" ?>
<advertisements>
<Ad>
<ImageUrl>
advertisement\A.JPEG </ImageUrl>
<NavigateUrl>http:www.facebook.com
</NavigateUrl>
<AlternateText>facebook
</AlternateText>
<Impression>
5 </Impression>
<TargetUrl>_blank</TargetUrl>
<Keyword>small</Keyword>
</Ad>
<Ad>
<ImageUrl>
advertisement\B.JPEG</ImageUrl>
<NavigateUrl>http:www.facebook.com
</NavigateUrl>
<AlternateText>facebook
</AlternateText>
<Impression>
5 </Impression>
<TargetUrl>_blank</TargetUrl>
<Keyword>small</Keyword>
</Ad>
</advertisements>
9 step :- Now go to web file where we have
kept the AdRotator control, and slect AdRatotor control, after select control a
AdRotator Tasks Bar will display like this (in screen shot)
10 step :- Now Click choose data source →
select data source (After click data source will display Data XML file Like
this (screen shot)
Click Browse →
select XML file which is created (Advertisement_XMLfile.xml → ok →ok (After ok
you can back on the web form)
Now
run the program
(3) Question: - Make a web page to display the
calendar control during internet web site executing using Calender control in
ASP.NET.
1 step : Start → visual studio → file →
new → project → web → ASP.NET application → (Give file name) like
Date_calender→ ok
2 step : (Select) Design Tab → ToolBox →
calendar (Drag and Drop on web page)
3. STEP :- Caption (Priorities of calendar,
Select Date )
4 STEP :- Right click of the mouse and
select view code after select view code the code display like this (code screen)
After that you
write the code
using System;
using
System.Collections; using System.Configuration; using System.Data;
using
System.Linq; using System.Web;
using
System.Web.Security; using System.Web.UI;
using
System.Web.UI.HtmlControls; using System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts; using System.Xml.Linq;
namespace WebApplication6
{
public partial
class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender,
EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToLongDateString();
Label2.Text = Calendar1.SelectedDate.ToShortDateString();
}
}
}
Now
run the programe (Ctrl + F5)
After
code write this is the output of the calendar
UPLOADING
FILES TO A WEB SERVER:- ASP.NET’s
FileUpload is an input controller used to upload files to a server. It appears
on the screen with a browse button and opens up a dialogue box to choose a file
or multiple files to upload from the local storage to the server. This is a
server-side control provided by ASP.NET. Implementing this feature is quite
easy.
ASP.NET has two
controls that allow users to upload files to the web server. Once the server
receives the posted file data, the application can save it, check it, or ignore
it. The following controls allow the file uploading:
(1) HtmlInputFile - an HTML server control
(2) FileUpload - and ASP.NET web control
Both controls
allow file uploading, but the FileUpload control automatically sets the
encoding of the form, whereas the HtmlInputFile does not do so.
We use the
FileUpload control. The FileUpload control allows the user to browse for and
select the file to be uploaded, providing a browse button and a text box for
entering the filename.
Once, the user
has entered the filename in the text box by typing the name or browsing, the
SaveAs method of the FileUpload control can be called to save the file to the
disk.
The
basic syntax of FileUpload is:-
<asp:FileUpload
ID= "Uploader" runat = "server" />
The FileUpload
class is derived from the WebControl class, and inherits all its members. Apart
from those, the FileUpload class has the following read-only properties:-
|
Properties |
Description |
|
FileBytes |
Returns an array of
the bytes in a file to be uploaded. |
|
FileContent |
Returns the stream
object pointing to the file to be uploaded. |
|
FileName |
Returns the name of
the file to be uploaded. |
|
HasFile |
Specifies whether
the control has a file to upload. |
|
PostedFile |
Returns a reference
to the uploaded file. |
The posted file
is encapsulated in an object of type HttpPostedFile, which could be accessed
through the PostedFile property of the FileUpload class.
The
HttpPostedFile class has the following frequently used properties:-
|
Properties |
Description |
|
ContentLength |
Returns the size of
the uploaded file in bytes. |
|
ContentType |
Returns the MIME
type of the uploaded file. |
|
FileName |
Returns the full
filename. |
|
InputStream |
Returns a stream
object pointing to the uploaded file. |
Example:-
The
following example demonstrates the FileUpload control and its properties. The
form has a FileUpload control along with a save button and a label control for
displaying the file name, file type, and file length.
In the design
view, the form looks as follows:-
The content
file code is as given:-
<body>
<form id="form1"
runat="server">
<div>
<h3> File Upload:</h3>
<br />
<asp:FileUpload
ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="btnsave"
runat="server" onclick="btnsave_Click" Text="Save"
style="width:85px" />
<br /><br />
<asp:Label
ID="lblmessage" runat="server" />
</div>
</form>
</body>
The
code behind the save button is as given:-
protected void
btnsave_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
if (FileUpload1.HasFile)
{
try
{
sb.AppendFormat(" Uploading file:
{0}", FileUpload1.FileName);
//saving the file
FileUpload1.SaveAs("<c:\\SaveDirectory>"
+ FileUpload1.FileName);
//Showing the file information
sb.AppendFormat("<br/> Save
As: {0}",
FileUpload1.PostedFile.FileName);
sb.AppendFormat("<br/> File
type: {0}", FileUpload1.PostedFile.ContentType);
sb.AppendFormat("<br/> File
length: {0}",
FileUpload1.PostedFile.ContentLength);
sb.AppendFormat("<br/> File
name: {0}",
FileUpload1.PostedFile.FileName);
}catch (Exception ex)
{
sb.Append("<br/> Error
<br/>");
sb.AppendFormat("Unable to save
file <br/> {0}", ex.Message);
}
}
else
{
lblmessage.Text = sb.ToString();
}
}
THE END UNIT 4 ASP.NET
No comments:
Post a Comment
PLEASE DO LEAVE YOUR COMMENTS