Advanced Web Programming
Advanced Web Programming
T)
SEMESTER - V (CBCS)
ADVANCED
WEB PROGRAMMING
SUBJECT CODE: USIT503
© UNIVERSITY OF MUMBAI
Published by : Director,
Institute of Distance and Open Learning,
University of Mumbai,
Vidyanagari,Mumbai - 400 098.
2. The C# Language................................................................................................. 20
Unit 2
Unit 3
Unit 4
Unit 5
10
The Data Controls: The GridView, Formatting the GridView,
selecting a GridView Row, Editing with the GridView, Sorting and
Paging the GridView, Using GridView Templates, The DetailsView
and FormView
V XML: XML Explained, The XML Classes, XML Validation, XML
Display and Transforms.
Security Fundamentals: Understanding Security Requirements,
Authentication and Authorization, Forms Authentication, Windows
12
Authentication.
ASP.NET AJAX: Understanding Ajax, Using Partial Refreshes, Using
Progress Notification, Implementing Timed Refreshes, Working with
the ASP.NET AJAX Control Toolkit.
1.0 OBJECTIVE
• When an application is run for the first time, the common language
runtime just-in-time compiler compiles the MSIL code into native
code before it is executed.
• garbage collection,
• exception handling,
• These class libraries provide rich support for a wide range of tasks,
including data access, security, file IO, XML manipulation,
messaging, class reflection, XML Web services, user-interface
construction, text processing, ASP.NET, and Microsoft Windows
services.
• The most unique attribute of the .NET Framework is its support for
multiple languages.
22
Introducing .NET
This book uses the Visual Basic language, which enables you to create
readable, modern code. The .NET version of VB is similar in syntax to
older flavors of VB that you may have encountered, including “classic”
VB 6 and the Visual Basic for Applications (VBA) language often used to
write macros in Microsoft Office programs.
1.1.1 C#, VB, and the .NET Languages
• This book uses the Visual Basic language, which enables you to
create readable, modern code. The .NET version of VB is similar in
syntax to older flavors of VB that you may have encountered,
including “classic” VB 6 and the Visual Basic for Applications
(VBA) language often used to write macros in Microsoft Office
programs such as Word and Excel. However, you cannot convert
classic VB into the .NET flavor of Visual Basic, just as you cannot
convert C++ into C#.
44
Introducing .NET
• It is the IDE for coding with .net framework that spans the entire .net
framework.
Windows & COM+ services:
• Data Access
• Thread management
• XML support
66
1.1.4 Common Language Runtime Introducing .NET
• The CLR is built around the CTS, which defines standard, object-
oriented data types that are used across all .NET programming
languages.
• Code that runs under the control of the CLR is called managed code.
Managed code allows the CLR to do the following.
• handle exceptions
• Any .NET language can use the .NET class library’s features by
interacting with the right objects.
• Some parts of the class library include features you’ll never need to
use in web applications (such as the classes used to create desktop
applications with Windows interfaces). Other parts of the class
library are targeted directly at web development.
• These include the base set of classes that define common variable
types and the classes for data access, to name just a few.
• CTS defines standard, object oriented types and value types that are
supported by all .NET programming languages.
88
• CTS is the first prerequisite for allowing languages to interoperate. Introducing .NET
• Pointers
• Objects
• Interfaces
• Value types are simple data types that roughly correspond to simple
bit patterns like integers and floats.
• They are useful for representing simple data types, and nay not-
object user defined type, including enumerations.
• They are known as exact types which mean that they fully describe
the value they hold.
• They are self typing, which means that they describe their own
interface.
• They are very specific to the type of object you are assigning.
• Char
• int 8
• int 16
• float 32
• float 64
• unsigned int8
• unsigned int16
Type Safety:
• It checks whether the array index out of range or not, whether the
arithmetic exceptions are handled properly or not etc.
1.1.7 Metadata in .NET
Meta Data is organized information that the CLR uses to provide compile
time and runtime services, including:
• Memory Management
• Debugging
• Object Browsing
• Combine this with the fact that .NET components do not require
windows registry entries, and you can immediately appreciate why
deployments are so much easier in .NET.
10
10
The figure below illustrates different Meta Data Consumers: Introducing .NET
reflection
designers
debugger
profiler
Proxy generator
Schema serialization
Type Other IL Generator
Browser Compilers
• The CLS defines rules that range from naming conventions for
interface members, to rules governing method overloading.
13
Advanced Web WAP to accept a number from the user and check whether it is positive,
Programming
negative or zero.
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter The Number");
int num = Convert.ToInt32(Console.ReadLine());
if (num > 0)
{
Console.WriteLine("Positive Number");
}
if (num < 0)
{
Console.WriteLine("Negative Number");
}
if (num == 0)
{
Console.WriteLine("Number is ZERO");
}
Console.ReadKey(); // To hold the output
}
}
WAP to accept a number from the user and check whether it is even or
odd.
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter The Number");
int num = Convert.ToInt32(Console.ReadLine());
if (num % 2 == 0)
14
14
{ Introducing .NET
Console.WriteLine("Even Number");
}
else
{
Console.WriteLine("Odd Number");
}
Console.ReadKey(); // To hold the output
}
}
Fall-through in Switch
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter The Option");
int opt = Convert.ToInt32(Console.ReadLine());
switch (opt)
{
case 1:
Console.WriteLine("ONE");
goto case 3;
case 2:
Console.WriteLine("TWO");
break;
case 3:
Console.WriteLine("THREE");
break;
case 4:
Console.WriteLine("FOUR");
break;
default :
Console.WriteLine("Invalid Option");
15
Advanced Web break;
Programming
}
Console.ReadKey(); // To hold the output
}
}
While Loop
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Incremented Loop");
int i = 1;
while (i <= 10)
{
Console.Write(i + "\t");
i++;
}
Console.WriteLine("\nDecremented Loop");
int j = 10;
while (j >= 1)
{
Console.Write(j + "\t");
j--;
}
Console.ReadKey();
}
}
do while Loop
int i = 1;
do
{
Console.Write(i + "\t");
i++;
} while (i <= 10);
int j = 10;
16
16
do Introducing .NET
{
Console.Write(j + "\t");
j--;
} while (j > 0);
For Loop
Console.WriteLine("Incremented Loop");
for (int i = 1; i <= 10; i++)
{
Console.Write(i + "\t");
}
Console.WriteLine ("Decremented Loop")
for(int j=10;j>=1;j--)
{
Console.Write (j+"\t");
}
Foreach Loop
int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
1.6 SUMMARY
This chapter 1 gives the basic syntax of C#. It discusses about variables,
keywords, data types, creation of arrays, operators, control structures,
methods debugging and few example programs. After learning the above
topics, you can write many useful programs and built a strong foundation
for larger programming projects.
17
Advanced Web
Programming
1.7 EXERCISE: REVIEW QUESTIONS
Chapter 1
1) Write a note on .NET Framework.
2) Explain the data types in C#.
3) Explain the various operators in C#.
4) Discuss the various looping structures in C#.
5) Explain how arrays are created in C#.
6) What is a method? Explain its components.
7) How is debugging done in C#?
Program
1) WAP to accept a character from the user and check whether it is
vowel or not.
2) WAP to accept two numbers from the user and display the greater
number using if...else.
3) WAP to accept three numbers from the user and display the greater
number.
4) WAP to accept a year from the user and display whether it is leap
year or not.
5) WAP to accept a number from the user and display the factorial.
6) WAP to accept a number from the user and display sum of digits and
reverse of that number.
7) WAP to accept a number from the user and check whether it is
palindrom number or not.
8) WAP to accept a number from the user and check whether it is
armstrong number or not.
9) WAP to accept a number from the user and check whether it is
prime number or not.
10) WAP to accept two numbers from the user and display the GCD and
LCM of that numbers.
11) WAP to accept a number from the user and check whether it is
perfect number or not?
a. Example : 6 -> 1+2+3 = 6 28 = 1 + 2 + 4 + 7 + 14 = 28
18
18
12) WAP to display all the prime numbers between 1 to 1000? Introducing .NET
Numbers Factorials
1 1
2 2
3 6
4 24
5 120
6 720
1.8 REFERENCE
1) The Complete Reference: C#
2) Visual C# 2012: How to program.
3) https://docs.microsoft.com/en-us/dotnet/csharp/
19
Advanced Web
Programming
2
THE C# LANGUAGE
Unit Structure
2.0 The C# Language
2.1 Introduction
2.2 The .NET Languages
2.3 C# Language Basics
2.4 Variables and Data Types
2.5 Variables Operations
2.6 Keywords in C#
2.7 Object-Based Manipulation
2.7.1 The String Type
2.7.2 The Date Time and Time Span Types
2.7.3 The Array Type
2.8 Conditional Logic
2.8.1 Conditional Statements
2.9 Loops in C#
2.9.1 The for Loop
2.9.2 The foreach Loop
2.9.3 The While Loop
2.10 Methods in C#
2.10.1 Parameters
2.10.2 Method Overloading
2.11 Delegates
2.12 Summary
2.13 Questions
2.14 References
2.1 INTRODUCTION
20
20
language that uses C-like syntax (for example, Java), you’ll probably The C# Language
be most comfortable with C#. Or if you’ve spent a few hours writing
Microsoft Excel macros in VBA, you might prefer the natural style
of Visual Basic. Many developers become fluent in both. This
chapter presents an overview of the C# language.
• You’ll learn about the data types you can use, the operations you can
perform, and the code you’ll need to define functions, loops, and
conditional logic.
• This chapter assumes that you have programmed before and are
already familiar with most of these concepts—you just need to see
how they’re implemented in C#. If you’ve programmed with a
similar language such as Java, you might find that the most
beneficial way to use this chapter is to browse through it without
reading every section.
• This approach will give you a general overview of C#.
• You can then return to this chapter later as a reference when needed.
But remember, though you can program an ASP.NET application
without mastering all the language details, this deep knowledge is
often what separates the casual programmer from the true
programming guru.
• The .NET Framework ships with two core languages that are
commonly used for building ASP.NET applications: C# and VB.
• These languages are, to a large degree, functionally equivalent.
Microsoft has worked hard to eliminate language conflicts in the
.NET Framework.
• These battles slow down adoption, distract from the core framework
features, and makes it difficult for the developer community to solve
problems together and share solutions.
• According to Microsoft, choosing to program in C# instead of VB is
just a lifestyle choice and won’t affect the performance,
interoperability, feature set, or development time of your
applications.
• Surprisingly, this ambitious claim is essentially true.
• .NET also allows other third-party developers to release languages
that are just as feature-rich as C# or VB.
• These languages (which include Eiffel, Pascal, and even COBOL)
“snap in” to the .NET Framework effortlessly.
• In fact, if you want to install another .NET language, all you need to
do is copy the compiler to your computer and add a line to register it
in a configuration file.
21
Advanced Web • Typically, a setup program would perform these steps for you
Programming
automatically.
• Once installed, the new compiler can transform your code creations
into a sequence of Intermediate Language (IL) instructions, just as
the VB and C# compilers do with VB and C# code.
• IL is the only language that the Common Language Runtime (CLR)
recognizes.
• When you create the code for an ASP.NET web form, it’s changed
into IL using the C# compiler (csc.exe) or the VB compiler ().
Although you can perform the compilation manually, you’re more
likely to let ASP.NET handle it automatically when a web page is
requested.
• You just need to remember to put the semicolon at the end of the last
line to end the statement.
• You can find the curly braces to the right of most keyboards (next to
the P key); they share a key with the square brackets: [].
23
Advanced Web • But in each case, the curly braces play the same role, which makes
Programming
C# simpler and more concise than other languages that need a
different syntax for each type of block structure.
{
// Code statements go here.
}
Variables
• As with all programming languages, you keep track of data in C# by
using variables.
• Variables can store numbers, text, dates, and times, and they can
even point to full-fledged objects.
• When you declare a variable, you give it a name and specify the type
of data it will store.
• To declare a local variable, you start the line with the data type,
followed by the name you want to use. A final semicolon ends the
statement.
24
24
The C# Language
Reference Type
int number;
number = 4 + 2 * 3;// number will be 10.
number = (4 + 2) * 3;
// number will be 18.
• You can use all the standard types of variable operations in C#.
• When working with numbers, you can use various math symbols, as
listed in Table below C# follows the conventional order of
operations, performing exponentiation first, followed by
multiplication and division and then addition and subtraction. You
can also control order by grouping sub expressions with parentheses:
Operator Description Example
+ Addition 1 + 1 = 2
- Subtraction 5 - 2 = 3
* Multiplication 2 * 5 = 10
/ Division 5.0 / 2 = 2.5
% Gets the remainder left after integer division 7 % 3 = 1
• The operators above are designed for manipulating numbers.
However, C# also allows you to use the addition operator ( + ) to
join two strings:
26
26
// Join three strings together. The C# Language
myName = firstName + " " + lastName;
In addition, C# provides special shorthand assignment operators.
Here are a few examples:
// Add 10 to myValue. This is the same as myValue = myValue + 10;
myValue += 10;
// Multiple myValue by 3. This is the same as myValue = myValue * 3;
myValue *= 3;
// Divide myValue by 12. This is the same as myValue = myValue / 12;
myValue /= 12;
2.6 KEYWORDS IN C#
int mySmallValue;
long myLargeValue;
// Get the largest possible value that can be stored as a 32-bit integer.
// .NET provides a constant named Int32.MaxValue that provides this
number.
mySmallValue = Int32.MaxValue;
// This always succeeds. No matter how large mySmallValue is,
// it can be contained in myLargeValue.
myLargeValue = mySmallValue;
27
Advanced Web • On the other hand, narrowing conversions may or may not succeed,
Programming
depending on the data.
• This means that common data types have the built-in smarts to
handle basic operations (such as counting the number of characters
in a string).
• Even better, it means you can manipulate strings, dates, and numbers
in the same way in C# and in VB.
• You’ll learn far more about objects in Chapter 3. But even now it’s
worth taking a peek at the object underpinnings in seemingly
ordinary data types.
28
28
• In simple variables, a more useful result is returned: the string The C# Language
representation of the given variable.
string myString;
int myInteger = 100;
// Convert a number to a string. myString will have the contents
"100".
myString = myInteger.ToString();
• In the past, every language has defined its own specialized functions
for string manipulation.
• In .NET, however, you use the methods of the String class, which
ensures consistency between all .NET languages.
• Strings use zero-based counting. This means that the first letter is in
position 0, the second letter is in position 1, and so on. 29
Advanced Web • You’ll find this standard of zero-based counting throughout .NET
Programming
Framework for the sake of consistency.
Methods in System.String Class
Length() Returns the number of characters in the string (as an integer).
ToUpper() and ToLower()
Returns a copy of the string with all the characters changed to uppercase
or lowercase characters.
Trim(), TrimEnd(), and TrimStart()
Removes spaces (or the characters you specify) from either end (or both
ends) of a string.
PadLeft() and PadRight()
Adds the specified character to the appropriate side of a string as many
times as necessary to make the total length of the string equal to the
number you specify. For example, "Hi".PadLeft(5, '@') returns the string
@@@Hi.
Insert()
Puts another string inside a string at a specified (zero-based) index
position. For example, Insert(1, "pre") adds the string pre after the first
character of the current string.
Remove()
Removes a specified number of characters from a specified position. For
example, Remove(0, 1) removes the first character.
Replace()
Replaces a specified substring with another string. For example,
Replace("a", "b") changes all a characters in a string into b characters.
Substring()
Extracts a portion of a string of the specified length at the specified
location (as a new string). For example, Substring(0, 2) retrieves the first
two characters.
StartsWith() and EndsWith()
Determines whether a string starts or ends with a specified substring. For
example, StartsWith("pre") will return either true or false, depending on
whether the string begins with the letters pre in lowercase.
30
30
2.7.2 The DateTime and TimeSpan Types The C# Language
• The DateTime and TimeSpan data types also have built-in methods
and properties.
• The next example shows how you can use a TimeSpan object to find
the total number of minutes between two DateTime objects:
31
Advanced Web // Adding a TimeSpan to a DateTime creates a new DateTime.
Programming
DateTime myDate1 = DateTime.Now;
TimeSpan interval = TimeSpan.FromHours(3000);
DateTime myDate2 = myDate1 + interval;
// Subtracting one DateTime object from another produces a
TimeSpan.
TimeSpan difference;
difference = myDate2 - myDate1;
// Create a 4x2 array (a grid with four rows and two columns).
int[,] intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
int rows = intArray.GetUpperBound(0) + 1; // rows = 4
int columns = intArray.GetUpperBound(1) + 1; // columns = 2
Length
Returns an integer that represents the total number of elements in all
dimensions of an array. For example, a 3 × 3 array has a length of 9.
GetLowerBound() and GetUpperBound()
Determines the dimensions of an array. As with just about everything
in.NET, you start counting at zero (which represents the first dimension).
Clear()
Empties part or all of an array’s contents, depending on the index values
that you supply. The elements revert to their initial empty values (such as
0 for numbers).
IndexOf () and LastIndexOf ()
Searches a one-dimensional array for a specified value and returns the
index number. You cannot use this with multidimensional arrays.
Sort()
Sorts a one-dimensional array made up of comparable data such as strings
or numbers.
33
Advanced Web Reverse ()
Programming
Reverses a one-dimensional array so that its elements are backward, from
last to first.
• You can use all the comparison operators with any numeric types.
With string data types, you can use only the equality operators (==
and !=). C# doesn’t support other types of string comparison
operators.
int result;
result = String.Compare("apple", "attach"); // result = -1
result = String.Compare("apple", "all"); // result = 1
result = String.Compare("apple", "apple"); // result = 0
// Another way to perform string comparisons.
string word = "apple";
result = word.CompareTo("attach"); // result = -1
34
34
2.8.1 Conditional Statements The C# Language
The if Statement
• The if statement is the if (myNumber > 10)
powerhouse of conditional {
logic, able to evaluate any
combination of conditions // Do something.
and deal with multiple and }
different pieces of data. else if (myString == "hello")
• Here’s an example with an if {
statement that features two
else conditions: // Do something.
• An if block can have any }
number of conditions. If you else
test only a single condition, {
you don’t need to include any
else blocks. // Do something.
}
break;
default:
// Do something.
break;
}
2.8 LOOPS IN C#
Introduction
• Loops allow you to repeat a segment of code multiple times. C# has
three basic types of loops. You choose the type of loop based on the
type of task you need to perform. Your choices are as follows:
36
36
• You can loop a set number of times with a for loop. The C# Language
• You can loop through all the items in a collection of data by using a
foreach loop.
• You can loop while a certain condition holds true with a while or
do...while loop.
• The for and foreach loops are ideal for chewing through sets of data
that have known, fixed sizes.
value, and the amount to increment with each pass. Here’s one
example:
• You’ll notice that the for loop starts with parentheses that indicate
three important pieces of information. The first portion (int i = 0)
creates the counter variable (i) and sets its initial value (0).
• That means i will be equal to 0 for the first pass, equal to 1 for the
second pass, and so on. However, you could adjust this statement so
that it decrements the counter (or performs any other operation you
want).
37
Advanced Web • The middle portion (i < 10) specifies the condition that must be met
Programming
for the loop to continue. This condition is tested at the start of every
pass through the block. If i is greater than or equal to 10, the
condition will evaluate to false, and the loop will end.
2.8.2 The foreach Loop
• C# also provides a foreach loop that allows you to loop through the
items in a set of data.
• Instead, you create a variable that represents the type of data for
which you’re looking. Your code will then loop until you’ve had a
chance to process each piece of data in the set.
• For example, the next code segment loops through the items in an
array by using foreach.
• In this case, the foreach loop examines each item in the array and
tries to convert it to a string. Thus, the foreach loop defines a string
variable named element.
• For example, if you wanted to loop through an array and change the
values in that array at the same time, foreach code wouldn’t work.
38
38
The C# Language
int i = 0;
while (i < 10)
{
i += 1;
// This code executes ten times. }
• You can also place the condition at the end of the loop by using the
do...while syntax. In this case, the condition is tested at the end of
each pass through the loop:
int i = 0;
do
{
i += 1;
// This code executes ten times.
}
while (i < 10);
39
Advanced Web
Programming
2.9 METHODS IN C#
• Methods are the most basic building block you can use to organize
your code.
• By breaking down your code into methods, you not only simplify
your life, but also make it easier to organize your code into classes
and step into the world of object-oriented programming.
• When you declare a method in C#, the first part of the declaration
specifies the data type of the return value, and the second part
indicates the method name.
• If your method doesn’t return any information, you should use the
void keyword instead of a data type at the beginning of the
declaration.
40
40
The C# Language
private void MyMethodNoReturnedData()
{
// Code goes here.
}
• Private methods are hidden from view and are available only locally,
whereas public methods can be called by all the other classes in your
application.
• To really understand what this means, you’ll need to read the next
chapter, which discusses accessibility in more detail.
• If your method returns data, you have the option of using the data it
returns or just ignoring it:
2.9.1 Parameters
• Methods can also accept information through parameters.
Parameters are declared in a similar way to variables.
41
Advanced Web • Here’s how you might create a function that accepts two parameters
Programming
and returns their sum:
• Now you can look up product prices based on the unique product ID
or the full product name, depending on whether you supply an
integer or string argument:
decimal price;
// Get price by product ID (the first version).
price = GetProductPrice(1001);
// Get price by product name (the second version).
price = GetProductPrice("DVD Player");
• You cannot overload a method with versions that have the same
signature that is, the same number of parameters and parameter data
types because the CLR will not be able to distinguish them from
each other.
• When you call an overloaded method, the version that matches the
parameter list you supply is used. If no version matches, an error
occurs.
Optional and Named Parameters
43
Advanced Web
Programming
2.11 DELEGATES
• In other words, the method must have the same return type, the same
number of parameters, and the same data type for each parameter as
the delegate.
44
44
• This method accepts a single string argument and returns a string. The C# Language
• With those two details in mind, you can define a delegate that
matches this signature. Here’s how you would do it:
• Notice that the name you choose for the parameters and the name of
the delegate don’t matter.
• Once you’ve defined a type of delegate, you can create and assign a
delegate variable at any time. Using the String Function delegate
type, you could create a delegate variable like this:
• Using your delegate variable, you can point to any method that has
the matching signature. In this example, the StringFunction delegate
type requires one string parameter and returns a string. Thus, you
can use the functionReference variable to store a reference to the
TranslateEnglishToFrench() method
string frenchString;
frenchString = functionReference("Hello");
• Now that you have a delegate variable that references a method, you
can invoke the method through the delegate. To do this, you just use
the delegate name as though it were the method name:
StringFunction functionReference;
functionReference = TranslateEnglishToFrench;
2.12 SUMMARY:
This chapter 2 gives the basic syntax of OOP in C#. It discusses about
class, methods, constructors, destructor, method overloading and few
example programs. After learning the above topics, you can write many
useful programs and built a strong foundation for larger programming
projects.
45
Advanced Web
Programming
2.13 QUESTIONS
2.14 REFERENCES:
46
46
3
TYPES, OBJECTS, AND NAMESPACES
Unit Structure
3.0 Types, Objects, and Namespaces
3.1 Introduction
3.2 The Basics about Classes
3.2.1 Objects in C#
3.2.2 Constructors
3.2.3 Destructors
3.3 Building a Basic Class
3.3.1 Static Data Members and Member Functions
3.3.2 this Object in C#
3.3.3 Access Specifier
3.3.4 Adding Properties in Class
3.4 Value Types and Reference Types
3.5 Understanding Namespaces and Assemblies
3.5.1 using Keyword
3.5.2 Nested Namespace
3.5.3 Assemblies in C#
3.6 Advanced Class Programming
3.6.1 Inheritance in C#
3.6.2 Interfaces in C#
3.6.3 Delegates in C#
3.7 Summary
3.8 Questions
3.9 References
3.1 INTRODUCTION
• In this chapter, you’ll learn how objects are defined and how you
manipulate them in your code. Taken together, these concepts are
the basics of what’s commonly called object-oriented programming.
• This chapter explains objects from the point of view of the .NET
Framework.
• It doesn’t rehash the typical object-oriented theory, because
countless excellent programming books cover the subject. Instead,
you’ll see the types of objects .NET allows, how they are
constructed, and how they fit into the larger framework of
namespaces and assemblies.
47
Advanced Web
Programming
3.2 THE BASICS ABOUT CLASSES
Note:
Constructors in class are used for initializing new objects.
Fields are variables that provide the state of the class and its
objects, and methods are used to implement the behavior of
the class and its objects.
Syntax :
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}
48
48
3.2.1 Objects in C# Types, Objects, And
Namespaces
• It is a basic unit of Object-Oriented Programming and represents the
real-life entities.
• A typical C# program creates many objects, which as you know,
interact by invoking methods. An object consists of :
State: It is represented by attributes of an object. It also reflects the
properties of an object.
Behavior: It is represented by methods of an object. It also reflects the
response of an object with other objects.
Identity: It gives a unique name to an object and enables one object to
interact with other objects.
Consider Dog as an object and see the below diagram for its identity,
state, and behavior.
• All the instances share the attributes and the behaviour of the class.
But the values of those attributes, i.e. the state are unique for each
object. A single class may have any number of instances.
49
Advanced Web Syntax:
Programming
Classname objectname = new classname();
Example 1:
using System;
public class Student
{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void Main(string[] args)
{
Student s1 = new Student();//creating an object of Student
s1.id = 101;
s1.name = "Sonoo Jaiswal";
Console.WriteLine(s1.id);
Console.WriteLine(s1.name);
} }
3.2.2 Constructors
• Constructors are methods that are called when the object is first
created. To create an object, the constructor call is preceded by the
keyword “new”.
• The process of doing this is called instantiation.
• An object is then referred to as an instance of its class. They are
often used to initialize the data of an object.
• A constructor has the same name as the name of its type (name of
class).
• Its method signature includes only the method name and its
parameter list; it does not include a return type.
• Objects are allocated on the heap (a memory region allocated for the
program).
• Objects must be created with new Eg. Stack stk = new Stack(50);
• If you don't provide a constructor for your class, C# creates one by
default that instantiates the object and sets member variables to the
default values.
• If a constructor was declared, no default constructor is generated.
How constructors are different from a normal member function?
constructor.
• The advantage of a parameterized constructor is that you can
initialize each instance of the class with a different value.
using System;
namespace Constructor
{
class paraconstrctor
{
public int a, b;
public paraconstrctor(int x, int y) // declaring Parameterized
Constructor with int x, y parameter
{
a = x;
b = y;
}
}
class MainClass
{
static void Main()
{
paraconstrctor v = new paraconstrctor(100, 175); // Creating
object of Parameterized Constructor and int values
Console.WriteLine("-----------parameterized constructor
example by vithal wadje---------------");
Console.WriteLine("\t");
Console.WriteLine("value of a=" + v.a );
Console.WriteLine("value of b=" + v.b);
Console.Read();
}
}
}
53
Advanced Web 3) Copy Constructor in C#
Programming
• The constructor which creates an object by copying variables from
another object is called a copy constructor.
• The purpose of a copy constructor is to initialize a new instance to
the values of an existing instance.
using System;
namespace copyConstructor
{
class employee
{
private string name;
private int age;
public employee(employee emp) // declaring Copy constructor.
{
name = emp.name;
age = emp.age;
}
public employee(string name, int age) // Instance constructor.
{
this.name = name;
this.age = age;
}
public string Details // Get details of employee
{
54
54
get Types, Objects, And
Namespaces
{
return " The age of " + name +" is "+ age.ToString();
}
}
}
class empdetail
{
static void Main()
{
employee emp1 = new employee("Vithal", 23); // Create a new
employee object.
employee emp2 = new employee(emp1); // here is emp1
details is copied to emp2.
Console.WriteLine(emp2.Details);
Console.ReadLine();
}
}}
4) Static Constructor in C#
• When a constructor is created using a static keyword, it will be
invoked only once for all of the instances of the class and it is
invoked during the creation of the first instance of the class or the
first reference to a static member in the class.
• A static constructor is used to initialize static fields of the class and
to write the code that needs to be executed only once.
Some key points of a static constructor are:
• A static constructor does not take access modifiers or have
parameters.
• The user has no control over when the static constructor is executed
in the program.
5) Private Constructor in C#
• When a constructor is created with a private specifier, it is not
possible for other classes to derive from this class, neither is it
possible to create an instance of this class.
• They are usually used in classes that contain static members only.
Some key points of a private constructor are:
56
56
• Once we provide a constructor that is either private or public or any, Types, Objects, And
Namespaces
the compiler will not add the parameter-less public constructor to the
class.
using System;
namespace defaultConstructor
{
public class Counter
{
private Counter() //private constructor declaration
{
}
public static int currentView;
public static int visitedCount()
{
return ++ currentView;
}
}
class viewCountedetails
{
static void Main()
{
// Counter aCounter = new Counter(); // Error
Console.WriteLine("-------Private constructor example by
vithal wadje----------");
Console.WriteLine();
Counter.currentView = 500;
Counter.visitedCount();
Console.WriteLine("Now the view count is: {0}",
Counter.currentView);
Console.ReadLine();
}
}
}
57
Advanced Web 3.2.3 Destructors
Programming
• Destructors in C# are methods inside the class used to destroy
instances of that class when they are no longer needed.
• A Destructor has no return type and has exactly the same name as
the class name (Including the same case).
class Example
{
// Rest of the class
// members and methods.
// Destructor
~Example()
{
// Your code
}
}
3.2.4 Static Data Members and Member Functions
58
58
• We can define class members as static using the static keyword. Types, Objects, And
Namespaces
• When we declare a member of a class as static, it means no matter
how many objects of the class are created, there is only one copy of
the static member.
• The keyword static implies that only one instance of the member
exists for a class. Static variables are used for defining constants
because their values can be retrieved by invoking the class without
creating an instance of it.
• Static variables can be initialized outside the member function or
class definition. You can also initialize static variables inside the
class definition.
using System;
namespace StaticVarApplication {
class StaticVar {
public static int num;
59
Advanced Web Static Method
Programming
• A static method in C# is a method that keeps only one copy of the
method at the Type level, not the object level.
• That means, all instances of the class share the same copy of the
method and its data. The last updated value of the method is shared
among all objects of that Type.
• Static methods are called by using the class name, not the instance of
the class.
class StaticDemo
{
public static void withoutObj()
{
Console.WriteLine("Hello");
}
static void Main()
{
Program. withoutObj();
Console.ReadKey();
}
}
class Program
{
public int myVar; //a non-static field
static void Main()
{
StaticDemo p1 = new StaticDemo(); //an object of class
p1.myVar = 10;
p1.withoutObj();
Console.WriteLine(p1.myVar);
Console.ReadKey();
}
}
60
60
3.3.2 this Object in C# Types, Objects, And
Namespaces
• The “this” keyword in C# is used to refer to the current instance of
the class. It is also used to differentiate between the method
parameters and class fields if they both have the same name.
• Another usage of “this” keyword is to call another constructor from
a constructor in the same class.
• Here, for an example, we are showing a record of Students i.e: id,
Name, Age, and Subject. To refer to the fields of the current class,
we have used the “this” keyword in C#.
using System.IO;
using System;
class Student {
public int id, age;
public String name, subject;
class StudentDetails {
public static void Main(string[] args) {
Student std1 = new Student(001, "Jack", 23, "Maths");
61
Advanced Web Student std2 = new Student(002, "Harry", 27, "Science");
Programming
Student std3 = new Student(003, "Steve", 23,
"Programming");
Student std4 = new Student(004, "David", 27, "English");
std1.showInfo();
std2.showInfo();
std3.showInfo();
std4.showInfo();
}
}
62
62
class Person Types, Objects, And
Namespaces
{
private string name; // field
Example:
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
• In C#, these data types are categorized based on how they store their
value in the memory. C# includes the following categories of data
types:
• Value type
• Reference type
63
Advanced Web Value Type
Programming
• A data type is a value type if it holds a data value within its own
memory space. It means the variables of these data types directly
contain values.
• For example, consider integer variable int i = 100;
• The system stores 100 in the memory space allocated for the
variable i.
• The following image illustrates how 100 is stored at some
hypothetical location in the memory (0x239110) for 'i':
• As you can see in the above image, the system selects a random
location in memory (0x803200) for the variable s.
• The value of a variable s is 0x600000, which is the memory address
of the actual data value.
• Thus, reference type stores the address of the location where the
actual value is stored instead of the value itself.
The followings are reference type data types:
String
Arrays (even if their elements are value types)
Class
Delegate
Passing Reference Type Variables
• When you pass a reference type variable from one method to
another, it doesn't create a new copy; instead, it passes the variable's
address.
• So, If we change the value of a variable in a method, it will also be
reflected in the calling method.
65
Advanced Web
Programming static void ChangeReferenceType(Student std2)
{
std2.StudentName = "Steve";
}
static void Main(string[] args)
{
Student std1 = new Student();
std1.StudentName = "Bill";
ChangeReferenceType(std1);
Console.WriteLine(std1.StudentName);
}
Namespaces in C#
• Namespaces are used to organize the classes.
• It helps to control the scope of methods and classes in larger .Net
programming projects.
• The biggest advantage of using namespace is that the class names
which are declared in one namespace will not clash with the same
class names declared in another namespace.
• It is also referred as named group of classes having common
features.
• The members of a namespace can be namespaces, interfaces,
structures, and delegates.
• There are two types of namespaces.
1. User Defined Namespace
2. Build in Namespaces.
Defining a User-Defined Namespace
Example:
// defining the namespace name1
namespace name1
{
// C1 is the class in the namespace name1
class C1
{
// class code
}
}
66
66
using System; Types, Objects, And
Namespaces
namespace first_space {
class namespace_cl {
public void func() {
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space {
class namespace_cl {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
class TestClass {
static void Main(string[] args) {
first_space.namespace_cl fc = new first_space.namespace_cl();
second_space.namespace_cl sc = new
second_space.namespace_cl();
fc.func();
sc.func();
Console.ReadKey();
}
}
using System;
using first_space;
using second_space;
namespace first_space {
class abc {
public void func() {
Console.WriteLine("Inside first_space");
}
}
}
namespace second_space {
class efg {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
class TestClass {
static void Main(string[] args) {
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the
following result -
Inside first_space
Inside second_space
68
68
3.5.2 Nested Namespace Types, Objects, And
Namespaces
You can define one namespace inside another namespace as follows -
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
using System;
using first_space;
using first_space.second_space;
namespace first_space {
class abc {
public void func() {
Console.WriteLine("Inside first_space");
}
}
namespace second_space {
class efg {
public void func() {
Console.WriteLine("Inside second_space");
}
}
}
}
class TestClass {
static void Main(string[] args) {
abc fc = new abc();
efg sc = new efg();
fc.func();
sc.func();
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following
result -
Inside first_space
Inside second_space
69
Advanced Web 3.5.3 Assemblies in C#
Programming
• An assembly is a collection of types and resources that are built to
work together and form a logical unit of functionality.
• Assemblies take the form of executable (.exe) or dynamic link
library (. dll) files, and are the building blocks of .NET applications.
• An Assembly is a basic building block of .Net Framework
applications. It is basically a compiled code that can be executed by
the CLR.
• An assembly is a collection of types and resources that are built to
work together and form a logical unit of functionality. An Assembly
can be a DLL or exe depending upon the project that we choose.
Assemblies have the following properties:
• Assemblies are implemented as .exe or .dll files.
• For libraries that target the .NET Framework, you can share
assemblies between applications by putting them in the global
assembly cache (GAC). You must declare strong-name assemblies
before you can include them in the GAC.
• Assemblies are only loaded into memory if they are required. If they
aren't used, they aren't loaded. This means that assemblies can be an
efficient way to manage resources in larger projects.
Assemblies are basically the following two types:
1. Private Assembly
2. Shared Assembly
1. Private Assembly
• It is an assembly that is being used by a single application only.
• Suppose we have a project in which we refer to a DLL so when we
build that project that DLL will be copied to the bin folder of our
project.
• That DLL becomes a private assembly within our project. Generally,
the DLLs that are meant for a specific project are private assemblies.
2. Shared Assembly
• Assemblies that can be used in more than one project are known to
be a shared assembly.
• Shared assemblies are generally installed in the GAC.
• Assemblies that are installed in the GAC are made available to all
the .Net applications on that machine.
GAC(Global Assembly Cache)
• GAC stands for Global Assembly Cache. It is a memory that is used
to store the assemblies that are meant to be used by various
applications.
• Every computer that has CLR installed must have a GAC. GAC is a
location that can be seen at “C:\Windows\assembly” for .Net
70
70
applications with frameworks up to 3.5. For higher frameworks like Types, Objects, And
Namespaces
4 and 4.5 the GAC can be seen at:
“C:\Windows\Microsoft.NET\assembly\GAC_MSIL”.
Components of Assembly:
Assembly manifest :-
Information Description
Assembly A text string specifying the assembly name.
name
Version A major & minor version number & a revision & build
number number. The common language runtime uses this no. to
enforce version policy.
71
Advanced Web Culture Information on the culture or language the assembly
Programming
supports the information should be used only to
designate an assembly as a satellite assembly
containing culture or language specific information.
Strong name The public key from the publisher if the assembly has
Information been given a strong name.
Types of Inheritance
Multi-level inheritance
Multiple inheritance
Hierarchical Inheritance
• In this inheritance, more than one derived classes are created from a
single base class and further child classes act as parent classes for
more than one child classes.
• In the given example, class A has two children class B and class D.
Further, class B and class C both are having two children - class D
and E; class F and G respectively.
Hybrid inheritance
using System;
class A
{
public void displayA()
{
Console.WriteLine("Base Class Function");
}
}
class B : A
{
public void displayB()
{
Console.WriteLine("Derived Class Function");
}
}
74
74
class C : B Types, Objects, And
Namespaces
{
public void displayC()
{
Console.WriteLine("Derived Class Function");
}
}
class Programs
{
public static void Main(string[] args)
{
C obj = new C();
obj.displayA();
obj.displayB();
obj.displayC();
Console.ReadKey();
}
}
Hierarchical Inheritance
using System;
class A
{
public void displayA()
{
Console.WriteLine("Base Class Function");
}
}
class B : A
{
public void displayB()
{
Console.WriteLine("Derived Class Function");
}
}
class C : A
75
Advanced Web {
Programming
public void displayC()
{
Console.WriteLine("Derived Class Function");
}
}
class Programs
{
public static void Main(string[] args)
{
obj.displayA();
obj.displayC();
obj1.displayA();
obj1.displayB();
Console.ReadKey();
}
}
3.6.2 Interfaces in C#
76
76
Implementing an Interface Types, Objects, And
Namespaces
A class or a Struct can implement one or more interfaces using colon (:).
Syntax: <Class or Struct Name> : <Interface Name>
using System;
interface MyInterface
{
void display();
}
class CallInterface : MyInterface
{
public void display()
{
Console.WriteLine("Interface is called");
}
}
class CallInterface1 : MyInterface
{
public void display()
{
Console.WriteLine("Interface Method");
}
}
class Programs
{
public static void Main(string[] args)
{
CallInterface obj = new CallInterface();
CallInterface1 obj1 = new CallInterface1();
obj.display();
obj1.display();
Console.ReadKey();
}
}
77
Advanced Web using System;
Programming
interface Addition
{
void add(int n1, int n2);
}
interface Subtraction
{
void sub(int n1, int n2);
}
class CallInterface : Addition,Subtraction
{
public void add(int n1, int n2)
{
Console.WriteLine("Addition :" + (n1 + n2));
}
public void sub(int n1, int n2)
{
Console.WriteLine("Subtraction :" + (n1 - n2));
}
}
class Programs
{
public static void Main(string[] args)
{
CallInterface obj = new CallInterface();
obj.add(10,10);
obj.sub(100,10);
Console.ReadKey();
}
}
3.6.3 Delegates in C#
<accessmodifier>delegate<returntype><delegate_name>(<parameters>);
class DelegateMethod
{
public void display()
{
Console.WriteLine("Delegate is called");
}
}
Example
using System;
public delegate void MyDelegate(); // Step1
class DelegateMethod
{
public void display()
{
Console.WriteLine("Delegate is called");
}
}
80
80
class Programs Types, Objects, And
Namespaces
{
public static void Main(string[] args)
{
d();
Console.ReadKey();
}
}
Types of Delegate
1) Simple Delegate
• When delegate uses only one method to execute on the behalf of the
delegate then it is called as simple delegate.
2) Multicast Delegate
using System;
public delegate void MathOptr(int n1, int n2);
class DelegateMethod
{
public void add(int n1, int n2)
{
Console.WriteLine("Addition =" + (n1 + n2));
}
public void sub(int n1, int n2)
{
Console.WriteLine("Subtraction =" + (n1 - n2));
}
public void mult(int n1, int n2)
{
Console.WriteLine("Mult =" + (n1 * n2));
81
Advanced Web }
Programming
public void div(int n1, int n2)
{
Console.WriteLine("Div =" + (n1 / n2));
}
}
class Programs
{
public static void Main(string[] args)
{
d1(10, 20);
d2(20, 10);
d3(10, 10);
d4(20, 5);
MathOptr d5 = d1 + d2 + d3 + d4;
d5(10,2);
Console.ReadKey();
}
}
3.7 SUMMARY:
82
82
3.8 QUESTIONS: Types, Objects, And
Namespaces
3.9 REFERENCE:
83
Advanced Web
Programming
4
WEB FORM FUNDAMENTALS
4.0 Objectives
4.1 Introduction
4.2 An Overview
4.2.1 Writing Code
4.2.2 Using the Code-Behind Class
4.2.3 Adding Event Handlers
4.3 Understanding the Anatomy of an ASP.NET Application
4.3.1 ASP.NET File Types
4.3.2 ASP.NET Web Folders
4.3.3 Debugging
4.4 Introducing Server Controls
4.4.1 HTML Server Controls
4.4.2 View State
4.4.3 Using the Page Class
4.4.4 Using Application Events
4.4.5 Configuring an ASP.NET Application.
4.5 Questions
4.6 References
4.0 OBJECTIVES
4.1 INTRODUCTION
Web Forms are web pages built on the ASP.NET Technology. It executes
on the server and generates output to the browser. It is compatible to any
browser to any language supported by .NET common language runtime. It
is flexible and allows us to create and add custom controls.
84
84
4.2 AN OVERVIEW AWP
public partialclass_EventHandlerDemo:System.Web.UI.Page
{
protected void Page_Load(object sender, Event Args e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
}
}
Where object sender represents the object raising the event.
EventArgs represents the event arguments.
86
86
files, pages, handlers, modules and executable code that can be invoked AWP
from a virtual directory on the web server.
4.3.1 ASP.NET File Types
1) .aspx- This file is basically an extension of ASP.NET Web Pages. It
is used for web form pages.
2) .ascx – This extension is basically used for web form user controls.
The .ascx extension is often used for consistent parts of a website
like headers, footers etc.
3) .asmx – This extension is used for files that implement ASP.NET
Web Services.
4) .vb – This extension is used for VisualBasic.NET code modules.
These files are code-behind files and are used to separate code from
user interface.
5) .resx – These files are basically used for Windows Form Application
for storing resources such as text strings for internationalization of
applications.
6) Global.asax – These files are basically used to define Application-
and-Session level variables and start up procedures.
4.3.2 ASP.NET Web Folders
ASP.NET defines several special folders. These special folders can be
added to a Web site from Visual Studio menu system. We can add it by
right clicking the Website Application Project and selecting Add
ASP.NET folder.
The diagram shows the following :-
87
Advanced Web ASP.Net folders are as follows:-
Programming
1) App_Browsers - ASP.net reserve this folder name for storing
browser definition files. These files are used to determine the client
browser capabilities and have .browser extension.
2) App_Code – App_code folder can contain source code for utility
classes as well business objects (i.e .cs, .vb and .jsl files).The
Classes that are present in App_Code folder are automatically
compiled when your web application compiled.
3) App_Data - .App_Data folder is used by ASP.NET application for
storing ASP.NET application local database. App_Data is used to
store files that can be used as database files (.mdf and xml files).
Developers can also use this folder for storing data for their
ASP.NET Application.
4) App_GlobalResources - App_GlobalResources folder contains
resources (.resx and .resources files) that are compiled into
assemblies and have a global scope. These files are used to
externalize text and images from our application code. This also
helps us to support multiple languages and design-time changes
without recompilation of your source code. These files are strongly
typed and can be accessed programmatically.
5) App_LocalResources - App_LocalResources folder contains
resources (.resx and .resources files). These files are available to a
particular project, web page, master page or web user control.
6) App_Themes -These files contain subfolders that defines a specific
theme or look and feel for your Web site. These consist of files
(such as .skin, .css and image files) that defines the appearance of
Web pages and controls.
7) App_WebReferences – It contains Web references files (.wsdl,
.xsd, .disco, and .discomap files) that define references to Web
services.
8) Bin - Bin folder contains compiled assemblies (.dll files) for code
that we want to reference in our application. Assemblies in Bin
folder are automatically reference in our application.
4.3.3 Debugging
Debugging enables programmers to see how the Code works step-by-step,
how the variables values change, how objects are created and destroyed,
and so on. Debugging is the application’s method of inserting breakpoints.
Such breakpoints are used to pause running a program from running.
We start the debugging session using F5(Debug/Start Debugging). This
command starts our app with the debugger attached.
The Green arrow also starts the debugger
88
88
When running code in the debugger we often realize that we don’t need to AWP
see what happens to a particular function. We use some commands to skip
through code
89
Advanced Web
Programming
4.4 INTRODUCTION TO SERVER CONTROLS
The server controls are the heart of ASP.NET pages which represents
dynamic elements that our user can interact with. Server controls are tags
that are understood by the server. There are three kinds of server controls
1) HTML Server Controls – Traditional HTML tags.
2) Web Server Controls – New ASP.NET tags.
3) Validation server Controls – For input validation.
Advantages of Server Controls
Events Controls
ServerClick HtmlAnchor, HtmlButton, HtmlInputButton,
HtmlInputImage, HtmlInputReset
ServerChange HtmlInputText, HtmlInputCheckBox,
HtmlInputRadioButton, HtmlInputHidden,
HtmlSelect, HtmlTextArea
For example:- This example has one button and one textbox. When user
clicks the Button the result is shown in textbox
htmlcontrolsexample.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="html
controlsexample.aspx.cs"
Inherits="asp.netexample.htmlcontrolsexample" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Butto
n1_Click"/>
</body>
</html>
// htmlcontrolsexample.aspx.cs
using System;
namespace asp.netexample
{
91
Advanced Web public partial class htmlcontrolsexample : System.Web.UI.Page
Programming
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string a = Request.Form["Text1"];
Response.Write(a);
}
}
}
OUTPUT :-
When we click the button after entering text, it responses back to client.
93
Advanced Web
Programming
Properties Description
94
94
Trace Instance of the TraceContext class; performs tracing AWP
on the page.
95
Advanced Web Some points to remember about global.asax:-
Programming
1. They do not contain any HTML or ASP.NET tags.
2. Contain methods with specific predefined names.
3. They defined methods for a single class, application class.
4. They are optional, but a web application has no more than one
global.asax file.
How to add global.asax file:
Select Website >>Add New Item (or Project >> Add New Item if you're
using the Visual Studio web project model) and choose the Global
Application Class template.
After you have added the global.asax file, you will find that Visual Studio
has added Application Event handlers:
The Event Handling Methods are as follows:-
• Database connections
• Caching settings
• Session States
• Error Handling
• Security
Configuration file looks like this
<configuration>
<connectionStrings>
<add name=”myCon” connectionstring=”server=MyServer;
database=apeksha;uid=apekshashirke;pwd=mydata1223" />
</connectionStrings>
</configuration/>
Different types of configuration files
1) Machin.config :- Server or machine-wide configuration file.
2) Web.config :- Application configuration files which deal with a
single application.
97
Advanced Web Example :- Program to display the number of visitors currently browsing
Programming
your website
To Create a website and adding a webform to it
Adding a Global.asax to web applications
Add New Item>Global Application Class >Add
Global.asax
<%@ Application Language="C#" %>
<script runat=”server”>
void Application_Start(object sender, EventArgs e)
{
Application[“OnlineUsers’]=0; //application variable
}
void Application_End(object sender, EventArgs e)
{
//Code that runs on application shutdown
}
Void Application_Error(object sender, EventArgs e)
{
//Code that runs when an unhandled error occurs
}
Void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application[“OnlineUsers’]=(int) Application[“OnlineUsers’]-1;
Application.UnLock();
98
98
} AWP
</script>
Web.config
<?xml version=“1.0”>
<configuration>
<system.web>
<sessionState mode=”InProc” cookieless=”false” timeout=”1”/>
<compilation debug=”true” targetFramework=”4.5.2”/>
<httpruntime targetFramework=”4,5.2”/>
</system.web>
</configuration>
Default.aspx
<%@ Page Language=”C#” AutoEventWireup=”true”
CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<html xmlns=http://www.w3.org/1999/xhtml>
<head runat=”server”>
<title></title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
Visitors Count :<%=Application[“OnlineUsers”].ToString()%>
</div>
</form>
</body>
</html>
Where
99
Advanced Web
Programming
4.5 QUESTIONS:-
4.6 REFERENCES
https://developer.mozilla.org/en-US/docs/Learn/Forms/Your_first_form
https://www.oreilly.com/library/view/designing-web-
navigation/9780596528102/ch01.html
https://flylib.com/books/en/2.370.1.28/1/ (Anatomy of ASP.NET
application)
https://flylib.com/books/en/2.321.1.16/1/ (ASP.Net File Types)
https://www.c-sharpcorner.com/uploadfile/puranindia/special-folders-
in-asp-net/ (ASP.Net Web folders)
https://www.tutorialspoint.com/asp.net/asp.net_debugging.htm
(Debugging)
https://www.wideskills.com/aspnet/html-server-controls
https://www.c-sharpcorner.com/UploadFile/225740/what-is-view-state-
and-how-it-works-in-Asp-Net53/
100
100
5
FORM CONTROLS
Unit Structure
5.0 Form Controls
5.1 Stepping Up to Web Controls
5.2 Web Control Classes
5.2.1 Units
5.2.2 Enumerations
5.2.3 Colors
5.2.4 Fonts
5.2.5 Default Button
5.3 List Controls
5.4 Table Controls
5.5 Web Control Events and AutoPostBack
5.6 Validation Controls
5.7 Rich Controls
5.7.1 The Calendar
5.7.2 The AdRotator
5.7.3 Pages with Multiple Views
5.8 User Controls and Graphics
5.8.1 User Controls
5.8.2 Dynamic Graphics
5.8.3 The Chart Control
5.9 Website Navigation
5.9.1 The SiteMapPath Control
5.9.2 The Menu Control
5.9.3 The TreeView Control
5.10 Questions
5.11 References
ASP.NET is Fully Based on Controls. the use of controls can easily make any
Application without any problem in Asp.Net.There are some Types of
controls which are used in Asp.Net.
1. Web Forms Standard controls.
2. Navigation Controls
101
Advanced Web 3. Validation Controls
Programming
4. Web Parts controls
5. HTML Controls
Controls are building blocks in web form. Server controls are tags that are
understood by the server. Web server controls are special ASP.NET tags
understood by the server. Web server controls are also created on the
server and they require runat=”server” attribute to work. Basic Web
control include additional methods, events and properties
Web control classes are the basic control classes used in ASP.Net. Web
control classes are defined in System.Web.UI.WebControls namespace.
The following diagram shows the web control hierarchy
102
102
5) Login and security controls - These controls provide user AWP
authentication.
6) Master pages - These controls provide consistent layout and
interface throughout the application.
7) Navigation controls - These controls help in navigation. For
example, menus, tree view etc.
8) Rich controls - These controls implement special features. For
example, AdRotator, FileUpload, and Calendar control.
The syntax for creating web server control is:
<asp:control_name id=”some_id” runat=”server” />
Example :-
<asp:Button id=”btn1” Text=”Click Here” runat=”server”/>
Properties of web controls
1. AccessKey- Pressing this key with the Alt key moves focus to the
control.
2. BackColor, ForeColor – Used to change the color of the background
(BackColor) and text (ForeColor) of the control
3. BorderColor, BorderStyle, BorderWidth – Used to change the
border of control in the browser. Each of these three ASP.NET
properties maps directly to its CSS counterpart
4. CssClass – It is used to define the HTML class attribute for the
control in the browser.
5. Enabled - Indicates whether the control is grayed out.
6. Font – Used to define different font related settings such as Font-
Size, Font-Names and Font-Bold
7. Height, Width – It determines the height and width of the control in
the browser
8. TabIndex - Gets or sets the tab index of the Web server control.
9. ToolTip - Gets or sets the text displayed when the mouse pointer
hovers over the web server control.
10 Visible - It indicates whether a server control is visible.
11. UniqueID - Unique identifier.
12. SkinID - Gets or sets the skin to apply to the control.
13. Style - Gets a collection of text attributes that will be rendered as a
style attribute on the outer tag of the Web server control.
5.2.1 Units
Many properties of the controls use measurements such as Border width,
Height and Width. The values here requires the unit structure which
combines a numeric value with a type of measurement(pixels, percentage
and so on)
Example :- <asp:Label ID=”Label1” runat=”server” Height=”10px”
Text=”Label”> </asp:Label>
103
Advanced Web 5.2.2 Enumerations
Programming
Enumerations are used in heavily in the .NET class library to group a set
of related constants, which may use for collection type values for the
controls such as font names, colours or styles. For example, When you set
a controls BorderStyle property, we can choose one of the several
predefined values from the Borderstyle enumeration
Example :-
Button1.BorderStyle=BorderStyle.Dashed; //C#
<asp:Label BorderStyle=”Dashed” Text=”Border Test” ID=”lbl”
runat=”server” />
5.2.3 Colors
The color property refers to a color object from System.Drawing
namespace. we can create color objects in several ways:-
• ARGB(alpha,red,gren,blue) color value : we specify each value as
an integer from 0 to 255. The alpha component represents the
transparency of a color.
• predefined .NET color name : we choose the corresponding name
read-only property from color structure. These properties include the
140 HTML color names.
• HTML color name : we specify this value as a string by using the
ColorTranslator class.
Example :-
Label1.ForeColor=System.Drawing,Color.Red
Label1.ForeColor=System.Drawing.ColorTranslator.FromHtml(“#FF0000
”)
Label1.ForeColor=Color.Red
Label1.ForeColor= ColorTranslator.FromHtml(“#FF0000”)
5.2.4 Fonts
The Font Property actually references a full Font Info Object which
defines in the System. Web. UI. Web Controls namespace
Property Description
Name A String indicating the font name (such
as Verdana)
Names An array of strings with font names in
the order of preference. The browser will
use the first matching font that’s
installed on the user’s computer.
Size The size of the font as a FontUnit object.
This can represent an absolute or relative
size
Bold, Italic, Overline, Boolean properties that apply the given
Strikeout, Underline style attribute.
104
104
5.2.5 Default Button AWP
Default Button property ensures that whenever user presses Enter key the
button that is set as default will be triggered. we can set the default button
at the form level meaning of all the buttons in the form the one that is set
as default will be triggered whenever user presses Enter key.
Example :-
<form id="form1" runat="server" defaultbutton="Button1">
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick = "Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button"
OnClick = "Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="Button"
OnClick = "Button3_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
These controls are used to display the list with some list items in the page.
These controls include List Box, Drop Down List, Check Box List, Radio
Button List and Bulleted List. To add items to the list we have to define
<asp:ListItem> elements between the opening and closing tags of the
control.
1. ListBox
We can select multiple items from ListBox at a time.
Basic syntax of list box control:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
2. DropDownList
DropDownList control is used select single option from multiple listed
items.
Basic syntax of DropDown List :
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
105
Advanced Web Common properties of List Box and Drop Down List are as follows
Programming
Properties Description
SelectedValue Get the value of the selected item from the
dropdown list.
SelectedIndex Gets the index of the selected item from the
dropdown box.
SelectedItem Gets the text of selected item from the list.
Properties Description
Appearance Gets or sets a value determining the appearance of the
check box.
AutoCheck Gets or sets a value indicating whether the Checked or
CheckedState value and the appearance of the control
automatically change when the check box is selected.
CheckAlign Gets or sets the horizontal and vertical alignment of
the check mark on the check box.
Checked Gets or sets a value indicating whether the check box
106
106
is selected. AWP
4. RadioButtonList
Radio Button List Control is same as Drop Down List but it displays a list
of radio buttons that can be arranged either horizontally or vertically. We
can select only one item from the given Radio Button List of options.
Properties of Radio Button List
Properties Description
RepeatColumns It displays the number of columns of radio
buttons.
RepeatDirection It pacifies the direction in which the
controls to be repeated. The values
available are Horizontal and Vertical.
Default value is vertical.
RepeatLayout Determines whether the radio buttons
display in an HTML table.
5. Bulleted List
The bulleted list control creates bulleted lists or numbered lists.
Properties Description
Bulletstyle Determines the type of list. We can choose from
Numbered(1,2,3 …);Lower Alpha (a, b, c,…); Upper
Alpha(A,B,C,…);Lower Roman(i, ii, iii….)and Upper
Roman(I.II,III,…) and the bullet symbols Disc, Circle,
Square or Custom Image
107
Advanced Web
Programming
5.4 TABLE CONTROLS
Property Description
BackImageUrl An URL to an image is used as background
for the table
Caption The caption of the table.
CaptionAlign The alignment of the caption text.
CellPadding The space between the cell walls and content.
CellSpacing The space between cells.
GridLines The gridline format in the Table.
108
108
HorizontalAlign The horizontal alignment of the table in the page AWP
Sometimes we need to write the server code that will react immediately to
an event that occurs on the client. Some events, such as Click event of a
button take place immediately, because when clicked, the button posts
back the page. However, other actions do cause events but don’t trigger a
post back.
For example when user chooses a new item in a list (which triggers
SelectedIndexChanged event) or changes the text in a text box (the
TextChangedevent ). In these cases without post back your code has no
way to run.
ASP.NET handles this by giving you two options:
– To wait until the next post back to react to the event. For example
imagine you want to react to the SelectedIndexChanged event in a list. If
the user selects an item in a list, nothing happens immediately. But, if the
user clicks a button to post back the page, two events fire: ButtonClick
followed by ListBox.SelectedIndexChanged. And if you have several 109
Advanced Web controls, it’s quite possible for a single post back to result in several
Programming
change events, which fire one after the other, in an undetermined order.
– To use the automatic post back feature to force a control to post back the
page immediately when it detects a specific user action. In this scenario,
when the user clicks a new item in the list, the page is posted back, your
code executes, and a new version of the page is returned.
110
110
AutoPostBack in ASP.NET AWP
Example:-
Your Name : <br/>
<asp:TextBox runat=”server” id=”txtName”/>
<asp:RequiredFieldValidator runat=”server” id=”reqName”
ForeColor=”Red” controltovalidate”txtName” errormessage=”Please enter
your name !”/>
112
112
2. CompareValidator Control AWP
Property Description
Type It specifies the data type
ControlToCompare It specifies the value of the input control to compare
with.
ValueToCompare It specifies constant value to compare with.
Operator It specifies the comparison operator the available
values are Equal, NotEqual, GreaterThanEqual,
LessThan, LessThanEqual and DataTypeCheck.
113
Advanced Web 4. Regular Expression Validator Control
Programming
The RequiredExpressionValidator allows validating the input text by
matching against a pattern of regular expression. The regular expression is
set in the ValidationExpression property. The following table summarizes
the commonly used syntax construct for regular expressions.
Syntax:-
Example :-
Email ID :<br/>
<asp:TextBox runat=”server” id=”txtnumber”/>
114
114
<asp:RegularExpressionvalidator runat=”server” ForeColor=”Red” AWP
id=”rexNumber” controlToValidate =”txtnumber” errormessage=”Please
enter valid email address!”
ValidationExpression=”\w=([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-
.]\w+)*”>Please enter valid email
address!</asp:regularExpressionValidator>
5. CustomValidator
The CustomValidator control allows writing application specific custom
validation routines for both the client side and the server side
validation. The client side validation routine should be written in a
scripting language, such as JavaScript or VBScript, which the browser can
understand. The server side validation routine must be called from the
control's ServerValidate event handler. The server side validation routine
should be written in any .Net language, like C# or VB.Net.
Syntax:-
Rich controls are built with multiple HTML elements and contain rich
functionality. Examples of rich controls are the calendar control and
AdRotator.
5.7.1 The Calendar Control
The calendar control is used to display a calendar in the browser. This
control displays a one month calendar that allows the user to select dates
and move to the next and previous months. It is a functionality rich web
control which provides displaying one month at a time, selecting a day, a
week or a month, selecting a range of days moving from month to month
and controlling the display of the days programmatically.
Syntax:-
<asp:Calendar ID=”Calendar1” runat=”server”>
</asp:Calendar> 115
Advanced Web Properties and events of calendar control
Programming
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.
PrevMonthText Gets or sets the text for previous month navigation
control. The default value is <.
SelectedDate Gets or sets the selected date.
SelectedDates Gets a collection of Date Time objects
representing the selected dates.
SelectedDayStyle Gets the style properties for the selected dates.
SelectionMode Gets or sets the selection mode that specifies
whether the user can select a single day, a week or
an entire month.
SelectMonthText Gets or sets the text for the month selection
element in the selector column.
SelectorStyle Gets the style properties for the week and month
selector column.
SelectWeekText Gets or sets the text displayed for the week
selection element in the selector column.
ShowDayHeader Gets or sets the value indicating whether the
heading for the days of the week is displayed.
ShowGridLines Gets or sets the value indicating whether the
gridlines would be shown.
ShowNextPrevMonth Gets or sets a value indicating whether next and
previous month navigation elements are shown in
116
116
the title section. AWP
The calendar control has the following three most important events that
allow the developers to program the calendar control. They are
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.
Properties Description
Views Collection of View controls within the Multi View.
• Select Web User Control from the Add New Item dialog box and
name it footer.ascx. Initially, the footer.ascx contains only a Control
directive.
footer.ascx
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="footer.ascx.cs" Inherits="customcontroldemo.footer" %>
<table>
<tr>
<td align="center"> Copyright ©2010 TutorialPoints Ltd.</td>
</tr>
<tr>
<td align="center"> Location: Hyderabad, A.P </td>
</tr>
</table>
To add the user control to your web page, you must add the Register
directive and an instance of the user control to the page. The following
120
120 code shows the content file:
<%@ Page Language="C#" AutoEventWireup="true" AWP
CodeBehind="Default.aspx.cs" Inherits="customcontroldemo._Default"
%>
<%@ Register Src="~/footer.ascx" TagName="footer"
TagPrefix="Tfooter" %>
<!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>
<asp:Label ID="Label1" runat="server" Text="Welcome to
ASP.Net Tutorials "></asp:Label>
<br /> <br />
<asp:Button ID="Button1" runat="server"
onclick="Button1_Click" Text="Copyright Info" />
</div>
<footer:footer ID="footer1" runat="server" />
</form>
</body>
</html>
When executed, the page shows the footer and this control could be used
in all the pages of your website.
121
Advanced Web The Graphics Class
Programming
The Graphics class encapsulates Graphics Device interface drawing
surfaces. Before drawing any object we have to create surface using
Graphics class
Methods Description
DrawArc Draws an arc from the specified ellipse
DrawBeizer Draws a cubic beizer curve
DrawBeizers Draws a series of cubic Beizer curves
DrawClosedCurve Draw closed curve defined by array of points
DrawCurve Draws a curve defined by an array of points
DrawEllipse Draws an ellipse
DrawImage Draws an Image
DrawLine Draws a line
DrawPath Draws the lines and curves defined by a
GraphicsPath
DrawPie Draws the outline of a pie section
FillEllipse Fills the interior of an ellipse defined by
bounding rectangle.
FillPath Fills the interior of a path
FillPie Fills the interior of a pie section
FillPolygon Fills the interior of a polygon defined by an
array of points.
FillRectangle Fills the interior of a series of rectangles with a
Brush
FillRegion Fills the interior of a Region
Graphics Objects
After creating a Graphics object, You can use it draw lines, fill shapes and
draw text so on, The major objects are as follows:-
Methods Description
The chart control can create chart images of different types with many
formatting options and labels. It can create standard charts like area charts,
bar charts, column charts, line charts and pie charts along with more
specialized charts like stock charts with the provided data.
To fill the data for chart we can use datasource option for the database
values with the help of visual studio or we can provide the data from file
or collection.
• New Chart - Creates a new chart object and sets its width and height.
• AddTitle() – This method specifies the chart title
• AddSeries() – This method adds data to the chart
• chartType – This parameter defines the type of chart
• xValues – This parameter defines x-axis names
• yValues - This parameter defines the y-axis values
• Write() - method displays the chart
123
Advanced Web
Programming
5.9 WEBSITE NAVIGATION
Maintaining the menu of a large web site is difficult and time consuming.
In ASP.NET the menu can be stored in a file to make it easier to maintain.
This file is normally called web.sitemap, and is stored in the root
directory of the web.
Different Navigation Controls in ASP.NET
5.9.1 SiteMapPath Control:-
Site maps are XML files which are mainly used to describe the logical
structure of the web application. It defines the layout of all pages in web
application and how they relate to each other. Whenever you want you can
add or remove pages to your site map there by managing navigation of
website efficiently. Site map files are defined with .sitemap extension.
<sitemap> element is the root node of the sitemap file.
It has three attributes:
• Title: It provides textual description of the link.
• URL: It provides the location of the valid physical file.
• Description: It is used for tooltip of the link.
Properties of SiteMapPath Control:
• PathSeparator: This property is to get or set the out separator text.
• NodeStyle: This property is used to set the style of all nodes that
will be displayed.
• RootNodeStyle: This property is used to set the style on the
absolute root node.
• PathDirection: This property is used to set the direction of the links
generated in the output.
• CurrentNodeStyle: This property is used to set the style on node
that represent the current page.
• ShowToolTips: This property is used to set the tooltip for the
control. Default value is true.
• PathSeparatorStyle: This property is used to set the style of path
separator.
• pathSeparator: This property is to get or set the out separator text.
• NodeStyle: This property is used to set the style of all nodes that
will be displayed.
• RootNodeStyle: This property is used to set the style on the
absolute root node.
124
124
• PathDirection: This property is used to set the direction of the links AWP
generated in the output.
• CurrentNodeStyle: This property is used to set the style on node
that represent the current page.
• ShowToolTips: This property is used to set the tooltip for the
control. Default value is true.
• PathSeparatorStyle: This property is used to set the style of path
separator.
Creation of Site Map
Below is the HTML Markup of the Master Page Main.Master that contains
the SiteMapPath control as well as the SiteMapDataSource control.
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" Sho
wStartingNode="true" />
<asp:SiteMapPath ID="SiteMapPath1" runat="server" PathSeparator=">"
RenderCurrentNodeAsLink="false">
</asp:SiteMapPath>
<hr />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
Sitemap can be added using AddNewItemDialog of Visual Studio as
shown below.
126
126
DynamicMenuItemStyle Sets the style of the individual dynamic menu AWP
items
StaticSelectedStyle Sets the style of the selected static items.
DynamicSelectedStyle Sets the style of the selected dynamic items.
StaticHoverStyle Sets the mouse hovering style of the static items.
Properties Description
BackColor Gets or sets the background color for
the control.
5.10 QUESTIONS:-
128
128
5.11 REFERENCES AWP
https://www.tutorialride.com/asp-net/list-controls-in-asp-net.htm
https://w3schools.sinsixx.com/aspnet/control_table.asp.htm
https://www.tutorialspoint.com/asp.net/asp.net_multi_views.htm
https://www.dotnetfunda.com/tutorials/controls/menu.aspx
129
Advanced Web
Programming
6
ERROR HANDLING, LOGGING
AND TRACING
Unit Structure
6.0 Objective
6.1 Introduction
6.2 An Overview
6.3 Avoiding Common Errors
6.4 Understanding Exception Handling
6.4.1 The Exception Class
6.4.2 The Exception Chain
6.5 Handling Exceptions
6.5.1 Catch Specific Exceptions
6.5.2 Using Nested Exception Handlers
6.5.3 Exception Handling in Action
6.5.4 Mastering Exceptions
6.6 Throwing your own Exceptions
6.7 User-Defined Exceptions
6.8 Page Tracing
6.8.1 Enabling Tracing
6.8.2 Application Level Tracing
6.9 List of References
6.10 Unit End Exercise
6.0 OBJECTIVE
6.2 AN OVERVIEW
132
132
• Even if an error is the result of invalid input or the failure of a third- Error Handling,
Logging and Tracing
party component, an error page can shatter the professional
appearance of any application.
• The application users end up feeling that the application is unstable,
insecure, or of poor quality—and they’re at least partially correct.
136
136
A try statement looks like this: Error Handling,
Logging and Tracing
try
{
... // exception may get thrown within execution of this block
}
catch (ExceptionA e)
{
... // handle exception of type ExceptionA
}
catch (ExceptionB e)
{
... // handle exception of type ExceptionB
}
finally
{
... // cleanup code
}
Example
FileStream s = null;
try
{
s = new FileStream(curName, FileMode.Open);
...
}
catch (FileNotFoundException e)
{
Console.WriteLine("file {0} not found", e.FileName);
}
catch (IOException)
{
Console.WriteLine("some IO exception occurred");
} catch
{
Console.WriteLine("some unknown error occurred");
}
finally
{
if (s != null) s.Close();
} 137
Advanced Web
Programming
6.5.1 Catch Specific Exceptions
139
Advanced Web
Programming
Output
140
140 }
catch (DivideByZeroException err) Error Handling,
Logging and Tracing
{
// Report error here.
}
}
private decimal DivideNumbers(decimal number, decimal divisor)
{
if (divisor == 0)
{
DivideByZeroException err = new DivideByZeroException();
throw err;
}
else
{
return number/divisor;
}
}
Alternatively, you can create a .NET exception object and specify a
custom error message by using a different constructor:
private decimal DivideNumbers(decimal number, decimal divisor)
{
if (divisor == 0)
{
DivideByZeroException err = new DivideByZeroException( "You
supplied 0 for the divisor parameter. You must be stopped.");
throw err;
}
else
{
return number/divisor;
}
}
141
Advanced Web
Programming
Output:
Exception occurred
Result is 0
Output
• Request Details
• Trace Information
• Trace information shows the stages of processing that the page went
through before being sent to the client
• Control Tree
• The control tree shows you all the controls on the page, indented to
show their hierarchy (which controls are contained inside other
controls).
• These sections display the cookies that were sent by the web
browser with the request for this page and display the cookies that
were returned by the web server with the response.
• ASP.NET shows the content and the size of each cookie in bytes.
• Headers Collection
• This section lists all the HTTP headers. Technically, the headers are
bits of information that are sent to the server as part of a request.
• They include information about the browser making the request, the
types of content it supports, and the language it uses. In addition, the
ResponseHeadersCollection lists the headers that are sent to the
client as part of a response.
148
148
• Form Collection Error Handling,
Logging and Tracing
• This section lists the variables and values submitted in the query
string. You can see this information directly in the web page URL in
the address box in the browser.
Server Variable
149
Advanced Web • Writing Trace Information
Programming
6.9 REFERENCES
152
152
7
STATE MANAGEMENT
Unit Structure
7.0 Objectives
7.1 Understanding the Problem of State
7.2 Using View State
7.3 Transferring Information between Pages
7.4 Using Cookies
7.5 Managing Session State
7.6 Configuring Session State
7.7 Using Application State
7.8 Using QueryString
7.9 Comparing State Management Options
7.10 List of References
7.11 Unit End Exercise
7.0 OBJECTIVE
• It only happens because of one server; all the controls of the Web
Page are created and after the round trip the server destroys all the
instances. So, to retain the values of the controls we use state
management techniques.
• In this method we will trace the user activity when user visits
multiple pages.
153
Advanced Web
Programming
7.2 USING VIEW STATE
View State
View State is the method to preserve the Value of the Page and Controls
between round trips. It is a Page-Level State Management technique.
View State is turned on by default and normally serializes the data in
every control on the page regardless of whether it is actually used during a
post-back.
Features of View State
These are the main features of view state:
• Stores the value of Pages and Control Properties defined in the page.
• Creates a custom View State Provider that lets you store View State
Information in a SQL Server Database or in another data store.
Advantages of View State
• Easy to Implement.
• No server resources are required: The View State is contained in a
structure within the page load.
• Enhanced security features: It can be encoded and compressed or
Unicode implementation.
154
154
Disadvantages of View State State Management
Security Risk: The Information of View State can be seen in the page
output source directly. We can manually encrypt and decrypt the contents
of a Hidden Field, but it requires extra coding. If security is a concern,
then consider using a Server-Based State Mechanism so that no sensitive
information is sent to the client.
Performance: Performance is not good if we use a large amount of data
because View State is stored in the page itself and storing a large value
can cause the page to be slow.
Device limitation: Mobile Devices might not have the memory capacity
to store a large amount of View State data.
It can store values for the same page only.
Example:
If we want to add one variable in View State,
ViewState["Var"]=Count;
For Retrieving information from View State
string Test=ViewState["TestVal"];
1. When we make request from client to web server, the web server
process the request and give the lot of information with big pockets
which will have Header information, Metadata, cookies etc., Then
repose object can do all the things with browser.
Cookie's common property:
Domain: This is used to associate cookies to domain.
Secure: We can enable secure cookie to set true (HTTPs).
Value: We can manipulate individual cookie.
Values: We can manipulate cookies with key/value pair.
Expires: Which is used to set expire date for the cookies.
Advantages of Cookie:
158
158
• SQLServer mode stores session state in a SQL Server State Management
database. This ensures that session state is preserved if the
Web application is restarted and also makes session state
available to multiple Web servers in a Web farm.
161
Advanced Web
Programming
7.10 REFERENCE
162
162
8
STYLES, THEMES AND MASTER PAGES
Unit Structure
8.0 Objectives
8.1 Styles
8.1.1 What is CSS?
8.1.2 Types of CSS
8.1.3 Types of CSS Selectors
8.2 Themes
8.3 Master Pages
8.4 List of References
8.5 Unit End Exercise
8.0 OBJECTIVE
8.1 STYLES
A style sheet is a file or form that is used in word processing and desktop
publishing to define the layout style of a document.
A style sheet contains the specifications of a document's layout, such as
the page size, margins, fonts and font sizes
8.1.1 What is CSS?
CSS stands for Cascading Style Sheets.
CSS saves a lot of work. It can control the layout of multiple web pages all
at once.
Cascading Style Sheets (CSS) is used to format the layout of a webpage.
With CSS, you can control the color, font, size of text, the spacing
between elements, how elements are positioned and laid out, what
background images or background colors are to be used, different displays
for different devices and screen sizes, and much more!
163
Advanced Web 8.1.2 Types of CSS
Programming
There are three types of CSS as follows:
• External CSS
• Internal CSS or Embedded CSS
• Inline CSS
External Style Sheet
The first way to add CSS style sheets to your web pages is through the
<link> element that points to an external CSS file.
For example the following <link> shows what options you have when
embedding a style sheet in your page:
<link href=”StyleSheet.css” rel=”Stylesheet” type=”text/css”
media=”screen” />
The href property points to a file within our site when we create links
between two pages. The rel and type attributes tell the browser that the
linked file is in fact a cascading style sheet. The media attribute enables us
to target different devices, including the screen, printer, and handheld
devices. The default for the media attribute is screen.
Embedded style sheet
The second way to include style sheets is using embedded <style>
elements. The <style> element should be placed at the top of your ASPX
or HTML page, between the <head> tags.
For example, to change the appearance of an <h1> element in the current
page alone, we can add the following code to the <head> of our page:
<head runat=”server”>
<style type=”text/css”>
h1
{
color: Blue;
}
</style>
</head>
Inline style sheet
The third way to apply CSS to your HTML elements is to use inline styles.
Because the style attribute is already applied to a specific HTML element,
we don’t need a selector and we can write the declaration in the attribute
directly:
<span style=”color: White; background-color: Black ;”>
This is white text on a black background.
164
164 </span>
8.1.3 Types of CSS Selectors Styles, Themes and Master
Pages
1) Universal Selector
The Universal selector, indicated by an asterisk (*), applies to all elements
in your page. The Universal selector can be used to set global settings like
a font family. The following rule set changes the font for all elements in
our page to Arial:
*{
font-family: Arial;
}
2) Type Selector
The Type selector enables us to point to an HTML element of a specific
type. With a Type selector all HTML elements of that type will be styled
accordingly.
h1
{
color: Green;
}
This Type selector now applies to all <h1> elements in your code and
gives them a green color. Type Selectors are not case sensitive, so you can
use both h1 and H1 to refer to the same heading.
3) ID Selector
The ID selector is always prefixed by a hash symbol (#) and enables us to
refer to a single element in the page. Within an HTML or ASPX page, we
can give an element a unique ID using the id attribute. With the ID
selector, we can change the behavior for that single element, for example:
#IntroText
{
font-style: italic;
}
Because we can reuse this ID across multiple pages in our site (it only
must be unique within a single page), you can use this rule to quickly
change the appearance of an element that you use once per page, but more
than once in our site, for example with the following HTML code:
<p id=”IntroText”>I am italic because I have the right ID. </p>
165
Advanced Web 4) Class Selector
Programming
The Class selector enables us to style multiple HTML elements through
the class attribute. This is handy when we want to give the same type of
formatting to several unrelated HTML elements. The following rule
changes the text to red and bold for all HTML elements that have their
class attributes set to highlight:
.Highlight
{
font-weight: bold; color: Red;
}
The following code snippet uses the Highlight class to make the contents
of a <span> element and a link (<a>) appear with a bold typeface:
This is normal text but <span class=”Highlight”>this is Red and
Bold.</span>
This is also normal text but <a href=”CssDemo.aspx”
class=”Highlight”>this link is Red and Bold as well</a>
The link tag
The HTML <link> tag is used for defining a link to an external document.
It is placed in the <head> section of the document.
The <link> tag defines a link between a document and an external
resource.
The <link> tag is used to link to external style sheets.
Syntax:
<head><link rel="stylesheet" type="text/css"
href="theme.css"></head>
Example:
<html>
<head>
<title>HTML link Tag</title>
<link rel="stylesheet" type="text/css" href="default.css" />
</head>
<body>
<div>
<p>Welcome to our website. We provide tutorials on various
subjects.</p>
</div>
</body>
</html>
Where,
166
166
rel-can be used to specify the relationship of the target of the link to the Styles, Themes and Master
Pages
current page.
type-This attribute Provides information about the content type of the
destination resource, telling whether it's an HTML document, a JPG
image, an Excel document, etc.
href(uri)-The "href" attribute specifies the destination resource, which the
element is linking to. It may specify a resource in the same website or in
an external one.
8.2 THEMES
A theme decides the look and feel of the website. It is a collection of files
that define the looks of a page. It can include skin files, CSS files &
images.
We define themes in a special App_Themes folder. Inside this folder is
one or more subfolders named Theme1, Theme2 etc. that define the actual
themes. The theme property is applied late in the page's life cycle,
effectively overriding any customization we may have for individual
controls on our page.
There are 3 different options to apply themes to our website:
1. Setting the theme at the page level: The Theme attribute is added to
the page directive of the page.
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Defa
ult.aspx.cs "Inherits="Default" Theme="Theme1"%>
2. Setting the theme at the site level: to set the theme for the entire
website we can set the theme in the web.config of the website. Open
the web.config file and locate the <pages> element and add the
theme attribute to it:
<pagestheme="Theme1">
....
....
</pages>
3. Setting the theme programmatically at runtime: here the theme is set
at runtime through coding. It should be applied earlier in the page's
life cycle ie. Page_PreInit event should be handled for setting the
theme. The better option is to apply this to the Base page class of the
site as every page in the site inherits from this class.
Page.Theme = Theme1;
Uses of Themes
1. Since themes can contain CSS files, images and skins, you can
change colors, fonts, positioning and images simply by applying the
desired themes.
167
Advanced Web 2. We can have as many themes as we want, and we can switch
Programming
between them by setting a single attribute in the web.config file or
an individual aspx page. Also, we can switch between themes
programmatically.
3. Setting the themes programmatically, we are offering our users a
quick and easy way to change the page to their likings.
4. Themes allow us to improve the usability of our site by giving users
with vision problems the option to select a high contrast theme with
a large font size.
1. "Start" - "All Programs" - "Microsoft Visual Studio
2010"
2. "File" - "New Website" - "C# - Empty website" (to avoid
adding a master page)
3. Provide the web site a name, such as Using Skins or
whatever you wish and specify the location
4. Then right-click on the solution in the Solution Explorer
then select "Add New Item" - "Default.aspx page" .
Skin file
ASP.Net skins can only be used to apply the styles to the ASP.Net
controls. So in this article let us see the procedure for using ASP.Net
Skins.
First create the web application as in the following:
Add an ASP.Net Themes Folder
To use the themes in the web site, we need to add an ASP.Net Themes
folder by right-clicking on Solution Explorer as in the following:
After adding the theme folder, add the SkinFile.skin file by right-clicking
on the ASP.Net theme folder. The Solution Explorer will then look as
follows:
168
168
Styles, Themes and Master
Pages
Now add the ASP.Net controls inside the SkinFile. Skin and assign the
Style to the controls using their properties as in the following:
In the preceding source code, we are assigning the existing ASP.Net Skin
File at page level, the existing ASP.Net Skin automatically appears in the
box after using the Themes property in the page header.
169
Advanced Web Assigning the Skin to the ASP.Net Controls
Programming
To assign the skin to the ASP.Net controls, you need to assign it to the
control's SkinId Property as in the following:
ASP.NET master pages allow us to create a consistent layout for the pages
in our application.
• A single master page defines the look and feel and standard behavior
that we want for all of the pages (or a group of pages) in our
application.
• We can then create individual content pages that contain the content
we want to display.
• When users request the content pages, they merge with the master
page to produce output that combines the layout of the master page
with the content from the content page.
• Master pages actually consist of two pieces, the master page itself
and one or more content pages.
8.4 REFERENCE
172
172
9
ADO.NET FUNDAMENTALS
Unit Structure
9.1 Objectives
9.2 Understanding Databases
9.2.1 Relational Table Design
9.2.2 Types of relationships among the table
9.3 Introduction to ADO.NET
9.3.1 ADO.NET Architecture
9.4 Understanding Data Provider Model
9.5 Understanding SQL Basics
9.5.1 SQL Server Data Types
9.6 Configuring Database
9.7 Using Direct data access
9.8 Using Indirect data access
9.9 Summary
9.10 References
9.11 Unit End Exercises
9.1 OBJECTIVES:
173
Advanced Web • The relationship allows merging of data from several tables for
Programming
querying and reporting.
• This is accomplished by the use of keys which are used to uniquely
identify specific records in a table.
9.2.1 Relational table design:
PERSONAL
EmployeeID PayRate
EN1-10 $25.00
EN1-12 $27.50
EN1-15 $20.00
EN1-16 $19.00
EN1-19 $22.75
EN1-20 $23.00
From above, each record in the Personal table is about one employee. That
record relates to one, and only one, record in the Payroll table.
One to Many :
• It means a record in Table A can relate to zero, one, or many records
in Table B. Many records in Table B can relate to one record in
Table A.
• Look at the following tables about a company's Customers and
Orders.
CUSTOMERS
Customer Customer
Address City State Zip
ID Name
19 International
20151 Engel's Books Ryebrook NY 10273-9764
Dr
20493 Jamison Books 396 Apache Ave Fountain Valley CA 92708-4982
Gardening
20512 79 Gessner Pk Houston TX 77024-6261
Galore
20688 Books Abound 51 Ulster St Denver CO 80237-3386
ORDERS
Order Num Customer ID Order Date Ship Date Shipper
76654 20151 2/1/00 2/6/00 USPS
74432 20151 6/30/99 7/2/99 Federal Express
75987 20151 11/10/99 11/12/99 UPS
62922 20493 9/5/99 9/6/99 UPS
65745 20493 10/1/99 10/3/99 USPS
From above, the Customers table holds a unique record for each customer.
Each customer can (and, we hope, does) place many orders. Many records
in the Orders table can relate to only one record in the Customers table.
175
Advanced Web Many to many :
Programming
• It means a record in Table A can relate many records in Table B and
records in Table B can relate to many record in Table A.
• Look at the following tables about Employees and Projects.
EMPLOYEES
EmployeeID Last Name First Name ProjectNum
EN1-26 O'Brien Sean 30-452-T3
EN1-26 O'Brien Sean 30-457-T3
EN1-26 O'Brien Sean 31-124-T3
EN1-33 Guya Amy 30-452-T3
EN1-33 Guya Amy 30-482-TC
EN1-33 Guya Amy 31-124-T3
PROJECTS
ProjectNum ProjectTitle EmployeeID
30-452-T3 Woodworking Around The House EN1-26
30-452-T3 Woodworking Around The House EN1-33
30-452-T3 Woodworking Around The House EN1-35
30-457-T3 Basic Home Electronics EN1-26
30-482-TC The Complete American Auto Repair Guide EN1-33
31-124-T3 The Sport Of Hang Gliding EN1-26
Above, tables with a many-to-many relationship.
176
176
9.3.1 ADO.NET Architecture: ADO.NET Fundamentals
178
178
9.5 UNDERSTANDING SQL BASICS: ADO.NET Fundamentals
179
Advanced Web c. Selecting the data:
Programming
The SELECT command is used to select data from a database. The data
returned is stored in a result table, called the result set.
The following SQL statement selects the "CustomerName" and "City"
columns from the "Customers" table:
SELECT CustomerName, City FROM Customers;
The following SQL statement selects all the columns from the Customers"
table:
SELECT * FROM Customers;
181
Advanced Web Numeric Data Types
Programming
Requirements
183
Advanced Web Step 1
Programming
Now, Open Visual Studio 2015 Update 3, go to the File >> New >>
Project or use the shortcut key "Ctrl+Shift +N".
Step 2
Here, select Visual C# >> Web >> ASP.NET Web Application. Finally,
click "OK" button.
184
184
Step 3 ADO.NET Fundamentals
Here, you can select the template for your ASP.NET Application. We are
choosing "Empty" here. Now, click OK button.
Step 4
Now, open the project and look for the Solution Explorer.
185
Advanced Web Here, open the default .aspx. If you want a Webform, you can add the
Programming
page (Web Form). Add+New item (Ctrl+Shift+A).
Now, we can create a login page, using ASP.NET code. You need to
follow the drag and drop method. Here, we already created the login page.
Step 5
Now, open the project. If you want a SQL Server database, you can add
the page (SQL Server database). Add+New item (Ctrl+Shift+A).
Here, you can select Visual C# and choose SQL Server database.
Afterwards, click "OK" button.
186
186
ADO.NET Fundamentals
187
Advanced Web Step 6
Programming
Now, we can go to the Server Explorer and add your database. You can
click the Tables and afterwards, click Add New Table.
Now, open the new table and you can fill the data, which is like
(studentname, password) and afterwards, you click the Update.
188
188
Here, click database in update and subsequently click update the database. ADO.NET Fundamentals
189
Advanced Web Now, we can click on the right click and click Show Table Data.
Programming
Step 7
Now, you can add SQL Data Source. Drag and drop method. Here, click
Configure Data Source
190
190
Now, we can choose your database and click NEXT button. ADO.NET Fundamentals
Now, you can select the ConnectionString and Click NEXT button
Now, we can choose Specify columns from a table or view and afterwards,
click Next button.
191
Advanced Web Now, click Test Query.
Programming
• DataReader class is used to read the data from the database. It works
in forward only and reads the only mode and requires the connection
for the complete time. That is why we use it in connected
architecture.
• The forward only feature makes it an efficient way to read data.
Thus we can say, DataReader is connection-oriented and requires an
active connection while reading the data.
In order to make an object of the DataReader class, we never use the new
keyword instead we call the ExecuteReader() of the command object. For
e.g.
SqlCommand cmd= new SqlCommand(“Select * from Table”);
SqlDatareader rdr=cmd.ExecuteReader(cmd);
193
Advanced Web Here cmd.ExecuteReader() executes the command and creates the instance
Programming
of DataReader class and loads the instance with data.
194
194
• It can be said that DataAdapter acts as a mediator between the ADO.NET Fundamentals
application and database which allows the interaction in
disconnected architecture.
For example:-
public DataTable GetTable(string query)
{
SqlDataAdapter adapter = new SqlDataAdapter(query, ConnectionString);
DataTable Empl = new DataTable();
adapter.Fill(Empl);
return Empl;
}
In the above lines of code, the object of the SqlDataAdapter is responsible
for establishing the connection. It takes query and ConnectionString as a
parameter. The query is issued on the database to fetch the data.
ConnectionString allows connectivity with the database. The fill() of the
SqlDataAdapter class adds the Table.
9.9 SUMMARY:
195
Advanced Web
Programming
9.10 REFERENCES :
Reference Books:
• Beginning ASP.NET 4.5 in C# by Apress.
• Murach’s ASP.NET 4.6 Web Programming in C#2015 by SPD
• ASP.NET 4.0 programming by Tata McGrawHill.
• Programming ASP.NET by Microsoft Press
Web References:
• https://www.c-sharpcorner.com/
• https://www.aspsnippets.com/
• http://asp.net-informations.com/
196
196
10
DATA BINDING
Unit Structure
10.1 Objectives
10.2 Introduction to Data Binding
10.3 Using Single-Value Data Binding
10.4 Using Repeated-Value Data Binding
10.5 Working with Data Source Controls
10.5.1 The SqlDataSource Control
10.6 Summary
10.7 References
10.8 Unit End Exercises
10.1 OBJECTIVES:
197
Advanced Web
Programming
10.3 USING SINGLE-VALUE DATA BINDING:
• You use the multi-item data bound controls to display the entire or a
partial table. These controls provide direct binding to the data
source.
• You use the DataSource property of these controls to bind a database
table to these controls
198
198
• Some examples of multi-item data-bound controls are GridView, Data Binding
FormView, DetailsView, ListBox, DataList, DropDownList, and so
on.
• Example : Data Binding with List Controls
• Create and fill data object. We can use any type of collection like
ArrayList, Hashtable, Dictionary, Data Table, Data set object.
• Link the object to the respective control using Data Source property.
• Activate the binding using DataBind() method.
Let us take the following steps:
Step (1) : Create a new website. Add a class named booklist by right
clicking on the solution name in the Solution Explorer and choosing the
item 'Class' from the 'Add Item' dialog box. Name it as booklist.cs.
using System;
using System.Data;
using System.Configuration;
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 databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;
}
<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>
<tr>
<td style="width: 228px; height: 21px">
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>
</div>
</form>
Step (3) : Finally, write the following code behind routines of the
application:
202
202
public partial class _Default : System.Web.UI.Page Data Binding
{
protected void Page_Load(object sender, EventArgs e)
{
IList bklist = createbooklist();
if (!this.IsPostBack)
{
this.ListBox1.DataSource = bklist;
this.ListBox1.DataTextField = "Book";
this.ListBox1.DataValueField = "Author";
this.DropDownList1.DataSource = bklist;
this.DropDownList1.DataTextField = "Book";
this.DropDownList1.DataValueField = "Author";
this.RadioButtonList1.DataSource = bklist;
this.RadioButtonList1.DataTextField = "Book";
this.RadioButtonList1.DataValueField = "Author";
this.CheckBoxList1.DataSource = bklist;
this.CheckBoxList1.DataTextField = "Book";
this.CheckBoxList1.DataValueField = "Author";
this.DataBind();
}
}
203
Advanced Web bl = new booklist("PROGRAMMING IN C", "RICHI
Programming
KERNIGHAN");
allbooks.Add(bl);
return allbooks;
}
protected void ListBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
this.lbllistbox.Text = this.ListBox1.SelectedValue;
}
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
this.lbldrpdown.Text = this.DropDownList1.SelectedValue;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender,
EventArgs e)
{
this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;
}
protected void CheckBoxList1_SelectedIndexChanged(object sender,
EventArgs e)
{
this.lblchklist.Text = this.CheckBoxList1.SelectedValue;
}
}
204
204
Observe the following: Data Binding
• To use data binding with the data fetched from a database we need
to first create data source which will be DataReader or DataSet
object.
• DataReader offers the best performance, but it limits data binding to
a single control because it is a forward only reader. After it is
finished, it can’t go back to the beginning so it can’t be used in
another data binding operation.
• For this reason, a DataSet is more common choice.
• To fill DataSet use following steps. 205
Advanced Web • Create the DataSet.
Programming
• Create new table and add it to the DataSet.Tables collection.
• Define the structure of the table by adding DataColumn objects to
the DataTable.Column collection.
• Add the data using DataTable.NewRow() method.
Code :
<%@ Page Language="C#" %>
<%@Import namespace="System.Data.SqlClient" %>
<%@Import namespace="System.Data" %>
<html>
<body>
<head><TITLE>Bind Films data to a ListBox</TITLE>
<script runat="Server">
void Page_Load(object sender, EventArgs e)
{ if(!this.IsPostBack)
{
getMovies();
}
}
private void getMovies()
{
string cnstr=GetConnString(); // Get a connection string
SqlConnection conn = new SqlConnection(cnstr);
IDbCommand cmd = new SqlCommand();
cmd.Connection= conn;
conn.Open();
cmd.Connection=conn;
string sql="SELECT movie_id, movie_title FROM movies";
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
da.Fill(ds,"Movies");
dview = new DataView(ds.Tables["Movies"]);
dview.RowFilter = "movie_year < 1951";
// List box containing movies before 1951
ListBoxMovie.DataSource= dview;
ListBoxMovie.DataBind();
conn.Close();
206
206
} Data Binding
</script>
</head>
<FORM NAME="FORM1" runat=server>
<asp:ListBox id=”ListBoxMovie” dataValueField = "movie_ID"
dataTextField = "movie_title" AppendDataBoundItems=true Rows="10"
BackColor=#efefe4 font-size=9pt runat="server" >
<asp:ListItem Value=-1 Text="Select Movie" />
</asp:ListBox>
</FORM> </body> </html>
A data source control interacts with the data-bound controls and hides the
complex data binding processes. These are the tools that provide data to
the data bound controls and support execution of operations like
insertions, deletions, sorting, and updates.
207
Advanced Web
Programming Data source Description
controls
Methods Description
208
208
10.5.1 The SqlDataSource Control Data Binding
209
Advanced Web The following code snippet shows a data source control enabled for
Programming
data manipulation:
10.6 SUMMARY
• You use the multi-item data bound controls to display the entire or a
partial table.
• These are the tools that provide data to the data bound controls and
support execution of operations like insertions, deletions, sorting,
and updates.
210
210
10.7 REFERENCES: Data Binding
Reference Books:
• https://www.c-sharpcorner.com/
• https://www.aspsnippets.com/
• http://asp.net-informations.com/
211
Advanced Web
Programming
11
DATA CONTROLS
Unit Structure
11.1 Objectives
11.2 Introduction of Grid view
11.2.1 Creating a GridView
11.2.2 Properties of GridView
11.3 Formatting the GridView:
11.3.1 Numeric Format Strings
11.3.2 Time and Date Format Strings:
11.3.3.Styles
11.4 Creating Table in SQL Server Database
11.5 Selecting a GridView Row
11.6 Editing with the GridView
11.7 Sorting and Paging the GridView
11.8 Using GridView Templates
11.9 DetailsView
11.10 Form View
11.11 Summary
11.12 References
11.13 Unit End Exercises
11.1 OBJECTIVES:
The GridView control displays the values of a data source in a table. Each
column represents a field, while each row represents a record. The
GridView control supports the following features:
• Binding to data source controls, such as SqlDataSource.
• Built-in sort capabilities.
212
212
• Built-in update and delete capabilities. Data Controls
• To format the grid view you have to ensure that dates, currency and
other number values are in good format. Grid View has property
"DataFormatString" to apply formatting.
• You can change colors, fonts, borders and alignment of grid. Each
BoundField column provides a DataFormatString property that you
can use to configure the numbers and dates using a format string.
• Format strings are generally made up of a placeholder and format
indicator, which are wrapped inside curly brackets, like this: {0:C}
• Here 0 shows the value that will be formatted and the letter indicates
a predetermined format style. In this case C means currency format
which formats a number as a dollar.
<asp:BoundField DataField="Price" HeaderText="Price"
DataFormatString="{0:C}" HtmlEncode="false" />
213
Advanced Web Here we are going to discuss about few format strings.
Programming
11.3.1 Numeric Format Strings :
214
214
Example: Data Controls
Step 1 : Create a table named UserDetail with the columns UserID and
UserName. The table looks as below.
Step 3 : Drag the GridView control from the Data controls menu.
You will need to set the Bound column in order to see the text in the cells
of the GridView control.
215
Advanced Web .aspx source code
Programming
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm1.aspx.cs"
Inherits="WebApplication120.WebForm1" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
UserID:<asp:TextBox ID="TextBoxUserID" runat="server">
</asp:TextBox>
<br />
UserName:
<asp:TextBox ID="TextBoxUserName" runat="server">
</asp:TextBox>
<br />
<br />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateSelectButton="True"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2" AutoGenerateColumns="False">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True"
ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True"
ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
<Columns>
216
216
<asp:BoundField HeaderText="UserID" DataField="UserID" /> Data Controls
<asp:BoundField HeaderText="UserName"
DataField="UserName" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
See the following image of a GridView after setting
'AutoGenerateSelectButton=True'.
Step 4 : See the Design view of your GridView. You will find a Hyperlink
with a text as 'Select'.
217
Advanced Web
Programming
Step 5 : Now double-click on the page and write the following code for
binding the data with the GridView.
Source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication120
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
show();
}
private void show()
{
{
SqlConnection con = new SqlConnection("Data Source=.;
uid=sa; pwd=wintellect; database=Rohatash;");
string strSQL = "Select * from UserDetail";
218
218
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con); Data Controls
Selecting the row event is fired when you make a click on the select link.
If you need any particular item in that row you can easily select it using
the cells property. In the Gridview, double-Click on the
SelectedIndexChanged Event and write the following code:
219
Advanced Web protected void GridView1_SelectedIndexChanged(object sender,
Programming
EventArgs e)
{
TextBoxUserID.Text = GridView1.SelectedRow.Cells[1].Text;
TextBoxUserName.Text = GridView1.SelectedRow.Cells[2].Text;
}
Now run the application and select a row; that will show the selected row
data in the TextBoxes.
220
220
Data Controls
conn.Close();
gvbind();
}
protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e) {
int userid =
Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)
GridView1.Rows[e.RowIndex];
Label lblID = (Label) row.FindControl("lblID");
//TextBox txtname=(TextBox)gr.cell[].control[];
TextBox textName = (TextBox) row.Cells[0].Controls[0];
TextBox textadd = (TextBox) row.Cells[1].Controls[0];
TextBox textc = (TextBox) row.Cells[2].Controls[0];
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
GridView1.EditIndex = -1;
conn.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail",
conn);
SqlCommand cmd = new SqlCommand("update detail set name='" +
textName.Text + "',address='" + textadd.Text + "',country='" + textc.Text
+ "'where id='" + userid + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
gvbind();
//GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender,
GridViewPageEventArgs e) {
GridView1.PageIndex = e.NewPageIndex;
gvbind();
}
223
Advanced Web protected void GridView1_RowCancelingEdit(object sender,
Programming
GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
gvbind();
}
}
Save all or press "Ctrl+S" and hit "F5" to run the page, the page will look
as in the following image:
Edit the value(s) here and click on the Update link, it will update all the
data or to remove it click on the "Delete" link above the image shown.
224
224
In this article I will explain how to do paging and sorting in ASP.NET Data Controls
GridView.
The following is the step-by-step explanation.
Step1: Create a table in the database.
CREATE TABLE [dbo].[Teacher](
[TeacherId] [int] NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Status] [varchar](50) NULL,
[Nationality] [varchar](50) NULL,
[Grade] [nchar](10) NULL
) ON [PRIMARY]
Step 2: Create a new ASP.NET web application and drag a GridView
control in the Default.aspx design view. Set the property
AllowSorting="true".
Step 3: Write the following in the page load event:
if (!Page.IsPostBack)
{
gvTeacher.DataSource = BindGridView();
gvTeacher.DataBind();
}
Step 4: The BindGridView() method populates the data in the GridView.
Write the following method in the Default.aspx.cs file:
protected void gvTeacher_Sorting(object sender, GridViewSortEventArgs
e)
{
string sortingDirection = string.Empty;
if (direction == SortDirection.Ascending)
{
direction = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
direction = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(BindGridView());
225
Advanced Web sortedView.Sort = e.SortExpression + " " + sortingDirection;
Programming
Session["SortedView"] = sortedView;
gvTeacher.DataSource = sortedView;
gvTeacher.DataBind();
}
Note: GridViewSortEventArgs is used to perform GridView sorting.
There are two properties.
SortDirection specifies the direction to sort the GridView column, either
by ascending or descending order.
Step 5: Select the GridView and double-click on PageIndexChanging
.Write the following code:
protected void gvTeacher_PageIndexChanging(object sender,
GridViewPageEventArgs e)
{
gvTeacher.PageIndex = e.NewPageIndex;
if (Session["SortedView"] != null)
{
gvTeacher.DataSource = Session["SortedView"];
gvTeacher.DataBind();
}
else
{
gvTeacher.DataSource = BindGridView();
gvTeacher.DataBind();
}
}
Step 6: Now maintain the SortDirection (Ascending or Descending) in
ViewState by adding the following code.
public SortDirection direction
{
get
{
if (ViewState["directionState"] == null)
{
ViewState["directionState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["directionState"];
}
226
226
set Data Controls
{
ViewState["directionState"] = value;
}
}
Step 7: The First Name is in ascending order as in the following:
<asp:SqlDataSource ID="MyDataSource"
ConnectionString="<%$Connectionstrings:ERPConnectionString%>"
SelectCommand="SELECT * FROM Sample"
UpdateCommand="Update SAMPLE SET
Name=@Name,Description=@Description Where Code=@Code"
DeleteCommand="Delete SAMPLE Where Code=@Code"
runat="server"/>
GridView1.DataBind();
}
231
Advanced Web
Programming
}
protected void btnviewdataSP_Click(object sender, EventArgs e)
{
DS_USER.USERMST_SELECTDataTable UDT = new
DS_USER.USERMST_SELECTDataTable();
DS_USERTableAdapters.USERMST_SELECTTableAdapter
UAdapter = new
DS_USERTableAdapters.USERMST_SELECTTableAdapter();
UDT = UAdapter.SelectData();
GridView1.DataSource = UDT;
GridView1.DataBind();
}
protected void btnviewLINQ_Click(object sender, EventArgs e)
{
DataClassesDataContext Ctx = new DataClassesDataContext();
GridView1.DataSource = Ctx.USERMST_SELECT();
GridView1.DataBind();
}
}
Code:
<table>
<tr>
<td align="right">
Name :</td>
<td>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">
City :</td>
<td>
<asp:TextBox ID="txtcity" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSave" runat="server" onclick="btnSave_Click"
Text="SAVE" />
</td>
</tr>
<tr>
<td>
</td>
<td>
234
234
<asp:DetailsView ID="DetailsView1" runat="server" Data Controls
BackColor="LightGoldenrodYellow" BorderColor="Tan"
BorderWidth="1px" CellPadding="2" DataKeyNames="ID"
ForeColor="Black" GridLines="None" Height="50px"
onitemdeleting="DetailsView1_ItemDeleting"
onitemupdating="DetailsView1_ItemUpdating"
onmodechanging="DetailsView1_ModeChanging"
onpageindexchanging="DetailsView1_PageIndexChanging"
Width="125px">
<FooterStyle BackColor="Tan" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<EditRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite"
/>
<AlternatingRowStyle BackColor="PaleGoldenrod" />
</asp:DetailsView>
</td>
</tr>
</table>
Now, After doing this next step to bind the DetailsView control from
Database.
Here, we first insert record in to database and fetch record from database
and display it to DetailsView control in ASP.Net.
Write below code on SAVE button for insert and bind data to DetailsView
in ASP.net.
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection SQLConn = new SqlConnection("Data
Source=COMPUTER_1\\SQLEXPRESS;Initial
Catalog=BOOK;Integrated Security=True");
SqlDataAdapter SQLAdapter = new SqlDataAdapter("insert into
UserMst values ('"+ txtname.Text +"','"+ txtcity.Text +"')", SQLConn);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
BindDetailsView();
}
private void BindDetailsView()
{
235
Advanced Web SqlConnection SQLConn = new SqlConnection("Data
Programming
Source=COMPUTER_1\\SQLEXPRESS;InitialCatalog=BOOK;Integrat
ed Security=True");
SqlDataAdapter SQLAdapter = new SqlDataAdapter("select * from
UserMst", SQLConn);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
DetailsView1.DataSource = DT;
DetailsView1.DataBind();
}
The Output of DetailsView control example is :
Note : If you use DetailsView control in your website, then it can display
a single record at a time, so you must have do paging with DetailsView
control for show all the records one by one.
The Form View control is used to display a single record at a time from a
data source. When you use the Form View control, you create templates to
display and edit data-bound values. The templates contain controls,
binding expressions, and formatting that define the look and functionality
of the form.
Step 1 - Create database table in SQL server
CREATE TABLE [dbo].[StudentsResult](
[RollNumber] [int] IDENTITY(10000,1) NOT NULL,
[StudentName] [nvarchar](50) NULL,
[Hindi] [int] NULL,
[English] [int] NULL,
[Physics] [int] NULL,
[Chemistry] [int] NULL,
[Biology] [int] NULL,
[Mathematics] [int] NULL,
236
236 [Total_Marks] [int] NULL,
[Percentage] [float] NULL, Data Controls
<td><%#Eval("Percentage")%></td>
</tr>
</table>
</ItemTemplate>
</asp:FormView>
</div>
</form>
</body>
</html>
Step 4 : Right click and view web form code. Write the following code.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace BindDataControl_Demo
{
public partial class FormView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFormView();
}
}
Screenshot:
11.10 SUMMARY:
11.11 REFERENCES :
Reference Books:
Web References:
• https://www.c-sharpcorner.com/
• https://www.aspsnippets.com/
• http://asp.net-informations.com/
241
XML
12
EXTENSIBLE MARKUP LANGUAGE (XML)
Unit Structure
12.0 Overview
12.1 XML Explained
12.2 The XML Classes
12.3 XML Validation
12.4 XML Display and Transforms
12.5 Understanding Security Requirements
12.6 Authentication and Authorization
12.7 Windows Authentication
12.8 Understanding Ajax
12.9 Using Partial Refreshes
12.10 Using Progress Notification
12.11 Implementing Timed Refreshes
12.12 Working with the ASP.NET AJAX Control Toolkit
12.13 Summary
12.14 Questions
12.0 OVERVIEW
In this unit you will be able to learn some concepts about XML. A few of
the concepts are:
The XML file may be loaded at the beginning of the program or at a later
stage. In the same way as you can load a model from a file, you can also
load the corresponding data from a file. The example below shows how to
describe the dynamic classes Event and Alarm in XML format. These
classes will be created when the XML file is loaded. The Event class has
the ID attribute of type string. The Alarm class is a subclass of the Event
class that has two attributes, PerceivedSeverity, of type String, and
Acknowledged, a Boolean attribute that defaults to false. The Alarm class
inherits the ID attribute from the Event class.
<classes xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation = "ilog/cpl/schema/model.xsd">
<classes>
<class>
<name>Event</name>
<attribute>
<name>ID</name>
<javaClass>java.lang.String</javaClass>
</attribute>
</class>
<class>
<name>Alarm</name>
<superClass>Event</superClass>
<attribute>
<name>PerceivedSeverity</name>
<javaClass>java.lang.String</javaClass>
</attribute>
<attribute>
<name>Acknowledged</name>
<javaClass>java.lang.Boolean</javaClass>
244
244
<defaultValue>false</defaultValue> Extensible Markup
Language (XML)
</attribute>
</class>
</classes>
The dynamic classes created from an XML file can inherit from existing
classes.
245
XML A "valid" XML document must be well formed. In addition, it must
conform to a document type definition.
If an XML document is well-formed and has an associated Document
Type Declaration (DTD), then it is said to be a valid XML document. We
will study more about DTD in the chapter XML - DTDs
A raw XML file can be viewed in all major browsers. You cannot expect
XML files to be displayed as HTML pages. Most browsers will display an
XML document with color-coded elements. It is rather displayed in a
proper hierarchy with a plus (+) or minus (-) to the left of the elements. It
can be clicked to expand or collapse the element structure. To view raw
XML source, try to select "View Page Source" or "View Source" from the
browser menu.
Security has always been vitally important in the business world to ensure
the integrity of content and transactions, to maintain privacy and
confidentiality, and to make sure information is used appropriately.
However, in today’s web-based business environment, the means for
providing that security have changed. Using physical security, no longer
works as well as it did in the past when all the computing resources were
locked in a central computing room with all jobs submitted locally.
An essential requirement of new security standards is that they work
naturally with content created using eXtensible Markup Language (XML).
XML is being adopted widely for a growing variety of applications and
types of content. It is also forming the basis for distributed system
protocols to integrate applications across the Internet, such as Web
Services protocols. XML languages are text based and designed to be
extended and combined. It should be natural to provide integrity,
confidentiality and other security benefits to entire XML documents or
portions of these documents in a way that does not prevent further
processing by standard XML tools [ XMLRef ]. XML Security therefore
must be integrated with XML in such a way as to maintain the advantages 247
XML and capabilities of XML while adding necessary security capabilities. This
is especially important in XML-based protocols, such as XML Protocol
(XMLProt, Simple Object Access Protocol, SOAP), that are explicitly
designed to allow intermediary processing and modification of messages.
Older security technologies provide a set of core security algorithms and
technologies that can be used in XML Security, but the actual formats
used to implement security requirements are inappropriate for most XML
Security applications. One reason is that these standards use binary
formats that require specialized software for interpretation and use, even
for extracting portions of the security information. A second reason is that
these standards are not designed for use with XML and do not support
common XML technical approaches for managing content, such as
specifying content with uniform resource identifier strings (URIs) or using
other XML standard definitions for locating portions of XML content (like
XPath [ XPath ]). In addition, some existing security technologies assume
that security-specific software will be integrated with applications to
enable security. In practice, this is not always the case due to the details of
custom integration.
XML Security addresses these issues by defining a common framework
and processing rules that can be shared across applications using common
tools, avoiding the need for extensive customization of applications to add
security. XML Security reuses the concepts, algorithms and core
technologies of legacy security systems while introducing changes
necessary to support extensible integration with XML. This allows
interoperability with a wide range of existing infrastructures and across
deployments.
XML Security reduces barriers to adoption by defining the minimum
modular mechanisms to obtain powerful results. By employing existing
technologies and enabling use of XML paradigms and tools, XML
Security minimizes the need to modify applications to meet security
requirements.
249
XML Authentication Types:
• Windows Authentication
• Forms Authentication
• Passport Authentication
• None
250
250
Extensible Markup
Language (XML)
Such as,
What is AJAX?
Asynchronous JavaScript and XML (AJAX) is a development technique
used to create interactive web applications or rich internet applications.
AJAX uses a number of existing technologies together, including:
XHTML, CSS, JavaScript, Document Object Model, XML, XSLT, and
the XML Http Request object.
With AJAX, web applications can retrieve data from the server
asynchronously, in the background, without reloading the entire browser
page. The use of AJAX has led to an increase in interactive animation on
web pages.
Advantages
• Reduces the traffic travels between the client and the server.
• No cross browser pain.
• Better interactivity and responsiveness.
• With AJAX, several multipurpose applications and features can be
handled using a single web page(SPA).
• API's are good because those work with HTTP method and
JavaScrtipt.
251
XML Disadvantages
252
252
Let’s check below example: Extensible Markup
Language (XML)
Partial View Code:
1. <div id="wrapper">
2. @model IEnumerable<MyAppModels.StudentModel>
3. <table class="table">
4. <tr>
5. <th>
6. @Html.DisplayNameFor(model => model.FName)
7. </th>
8. <th>
9. @Html.DisplayNameFor(model => model.LName)
10. </th>
11. <th>
12. @Html.DisplayNameFor(model => model.Email)
13. </th>
14. <th>
15. @Html.DisplayNameFor(model => model.address.Details)
</th>
16. <th>
17. @Html.DisplayNameFor(model => model.address.Country)
</th>
18. <th>
19. @Html.DisplayNameFor(model => model.address.State)
20. </th>
21. <th></th>
22. </tr>
23. @foreach (var item in Model)
24. {
25. <tr>
26. <td>
253
XML 27. <input type="hidden" name="stid" id="stid" value="@ite
m.Id" />
28. @Html.DisplayFor(modelItem => item.FName)
29. </td>
30. <td>
31. @Html.DisplayFor(modelItem => item.LName)
32. </td>
33. <td>
34. @Html.DisplayFor(modelItem => item.Email)
35. </td>
36. <td>
37. @Html.DisplayFor(modelItem => item.address.Details)
38. </td>
39. <td>
40. @Html.DisplayFor(modelItem => item.address.Country)
</td>
41. <td>
42. @Html.DisplayFor(modelItem => item.address.State)
43. </td>
44. <td>
45. <button id="btnDelete" data-Id="@item.Id">Delete</button>
46. <button id="btnEdit" data-Id="@item.Id">Edit</button>
47. <button id="btnDetails" data-Id="@item.Id">Details</button>
48. </td>
49. </tr>
50. }
51. </table>
52. </div>
53. <div id="EditArea"></div>
54. <div id="DetailArea"></div>
254
254
Controller Code: Extensible Markup
Language (XML)
1. public ActionResult GetStudents()
2. {
3. var res = stude.GettAllStudents();
4. return View(res);
5. }
Ajax/JS Code
1. $("#Edit").click(function () {
2. var id = $(this).attr("data-Id");
3. $.ajax({
4. method: "POST",
5. url: "Home/Edit/" + id,
6. contentType: "application/json; charset=utf-8",
7. cache: false,
8. success: function (data) {
9. $("#EditArea").html(data);
10. },
11. error: function (err) {
12. console.log('Failed to get data' + err);
13. }
14. });
15. });
Edit Action:
1. public ActionResult Edit(int id)
2. {
3. var res = stude.GettAllStudents().Where(x=>x.Id==id);
4. return partiaView(res);
5. }
255
XML Partial View for Edit:
1. @model MyAppModels.StudentModel
2. <form action="/home/update">
3. Name:<input type="text" value="@model.Name">
4. .......other fields.....
5. <button type="submit">Update<button>
6. <form>
Ajax for Delete:
1. $("#Delete").click(function () {
2. var id = $(this).attr("data-Id");
3. $.ajax({
4. method: "POST",
5. url: "Home/Delete/" + id,
6. contentType: "application/json; charset=utf-8",
7. cache: false,
8. success: function (data) {
9. $("#wrapper").Html(data);
10. },
11. error: function (err) {
12. console.log('Failed to get data' + err);
13. }
14. });
15. });
Action for Delete:
1. public ActionResult Delete(int id)
2. {
3. var Student= stude.GettAllStudents().Where(x=>x.Id==id);
4. _context.Students.Remove(Student);
5. _context.SaveChanges();
6. return View("GetStudents",res);
7. }
256
256
When you clicked the delete link, it deletes the record and loads the View Extensible Markup
Language (XML)
as you want but the issue is that When you clicked on another record then
it shows an error" record not found" and this is because of the view
overload on the First view instead of refreshing it. You don't know how to
refresh it, instead of overload. From overload, you mean that the ajax code
load a Partial view on the already loaded view, and because of that the
error occurs and stays until you refresh the page.
12.13 QUESTIONS:
12.14 BIBLIOGRAPHY:
• Javapoint – https://www.javatpoint.com/xml-tutorial
• Tutorialspoint - https://www.tutorialspoint.com/xml/index.htm
• C-SharpCorner - https://www.c-sharpcorner.com/article/ajax-in-asp-
net/
260
260