Advance-Web-Technologies-UsingASP.NET-Lab-Manual
Advance-Web-Technologies-UsingASP.NET-Lab-Manual
ADVANCED WEB
TECHNOLOGIES LAB
Published by
Director
Institute of Distance and Open learning ,
University of Mumbai,Vidyanagari, Mumbai - 400 098.
Module I
1. Windows Forms Application, Classes And Objects, Ui 1
Module II
2. Introduction To Asp.Net 24
3. Variables, Data Types, Operators And Objects In Asp.Net 36
4. Basic Server-Side Control 46
Module III
5. Database Programming In Asp.Net 58
6. Databound Controls In Asp.Net 103
Module IV
7. Session Management 119
8. Ajax 129
Module V
9. Web Services And Wcf 137
Module VI
10. Designing Mvc Application 151
11. View 195
*****
Syllabus
*****
MODULE I
1
WINDOWS FORMS APPLICATION,
CLASSES AND OBJECTS, UI
Unit Structure
1.0 Objectives
1.1 Introduction
1.2 Overview
1.3 Windows Forms Application
1.4 Classes and Objects
1.5 UI Controls
1.6 Inheritance
1.7 Interfaces
1.8 Abstract Classes
1.9 Summary
1.10 Unit End Exercises
1.11 List of References
1.0 OBJECTIVES
This chapter would make the learners to understand:
The basics of data types, decision making statements and keywords of
C# language.
The practical implementation of web form application.
The concepts of defining methods and objects.
The usage of various User Interface controls in web forms.
The Inheritance and interfacing concepts to be applied in C#
programs.
1.1 INTRODUCTION
C# is Microsoft‟s premier language for .NET development. It leverages
time-tested features with cutting-edge innovations and provides a highly
usable, efficient way to write programs for the modern enterprise
computing environment. It is, by any measure, one of the most important
languages of the twenty-first century.
Features of C#:
It is simple: The symbols like -> and :: in C++ are removed in this.
1
Object oriented: It is truly object oriented and supports Encapsulation, Windows Forms Application,
Classes And Objects, Ui
Inheritance
The entire C# class model is built on top of the Virtual Object System of
the
Applications of C#:
It can be used for a variety of applications that are supported by the .NET
platform:
Console applications
Windows applications
Developing Windows controls
2
Advanced Web Technologies Developing ASP.NET projects:
Creating Web controls
Providing Web services
Developing NET component library
3
1.2.1 A Simple program: Windows Forms Application,
Classes And Objects, Ui
To see the output of the above C# program, we have to compile it and run
it by pressing Ctrl + F5 or clicking the Run button or by clicking the
"Debug" menu and clicking "Start Without Debugging".
Data Types:
Variable: It is used to store the data value in a storage location and takes
different values during the execution time based on the input to be given.
These variables are represented through the defined data types. C# has two
main categories of data types such as i) value types and ii) reference types.
The other types are coming under these categories as given in Table 1.1.
Examples
S.No. Data Types datatype <variable_name>
= value;
1. Integers int a = 99;
Predefined
Types 2. Real Numbers float b=99.9f;
(Simple 3. Booleans bool c = true;
Types)
4. Characters char d = 'E';
Value
1 enum fruits{ apple, orange,
Types 1. Enumerations
grapes}
User- struct Coordinate
defined {
Types 2. Structure public int x;
public int y;
}
1. Objects public class Car{
public model { get; set; }
public int year { get; set;
Reference Predefined }
2
Types Types public string color{ get;
set; }
}
2. Strings string msg=”Happy”;
5
1. Classes public class MyClass { } Windows Forms Application,
Classes And Objects, Ui
2. Arrays var num = new int[]{
1,2,3,4,5};
3. Delegates public delegate void
User- MyDelegate(string msg);
defined 4. Interfaces interface IFile
Types {
void ReadFile();
void WriteFile(string
text);
}
int x = 4000;
3 Pointers (type *var-name; )
int* y = &x;
Key words:
C# language is defined by its keywords which determine the features built
into the language.
In general there are two types of keywords: reserved and contextual.
The reserved keywords shown in Table 1.2 cannot be used as names for
variables, classes, or methods.
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using virtual volatile
void while
Table 1.2 Reserved Keywords
add dynamic from get global
group into join let orderby
partial remove select set value
var where yield
Table 1.3 Contextual keywords
6
Advanced Web Technologies Decision Making Statements:
if Statement:
If (condition) statement; if (10<i)
else statement; {
Console.WriteLine("You are
Correct");
}
if(condition) if (10<i)
{ {
statement sequence Console.WriteLine("You are Correct");
} }
else else
{ {
statement Console.WriteLine("Check the value of
sequence i");
} }
if-else-if Ladder:
If (condition) if (10<i)
statement; {
else if (condition) Console.WriteLine("You are Correct");
statement; elseif (10<j)
else if (condition) Console.WriteLine("You are almost
statement; Correct");
... else
else Console.WriteLine("Check the value of I
statement; and j")
}
7
while(condition) statement while (n<=10){ Windows Forms Application,
Classes And Objects, Ui
Console.WriteLine("Value of n is :", n);
n=n+2;
}
do { do{
statements; sum= sum+n;
} while (condition); Console.WriteLine);
n=n+2;
} while (n <= 20);
8
Advanced Web Technologies PROGRAM TO ADD TWO NUMBERS:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
textBox3.Text = c.ToString();
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
9
Output: Windows Forms Application,
Classes And Objects, Ui
10
Advanced Web Technologies // declare instance variables
access type var1;
access type var2;
// declare methods
access ret-type method1(parameters)
{
// body of method
}
}
Defining a class:
Buildings have the information about houses, stores, offices, and so on.
This class is named as Building, and it will store three items of
information about a building: the number of floors, the total area, and the
number of occupants.
Demo program 2: Design Applications using Classes and Object
using System;
namespace MCAClassObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//Creating object
Calculator calObject = new Calculator();
Console.Write("Enter number1 : ");
int n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number2 : ");
int n2 = Convert.ToInt32(Console.ReadLine());
11
Console.WriteLine("The Sum of Two numbers is : " + result1); Windows Forms Application,
Classes And Objects, Ui
Console.WriteLine("The Subtraction of Two numbers is : " + result2);
Console.WriteLine("The Multiplication of Two numbers is : " + result3);
Console.ReadKey();
}
}
1.5 UI CONTROLS
Design a Web Application for an Organization with Registration
forms and advanced controls:
12
Advanced Web Technologies
Coding:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Registration
{
public partial class Form1 : Form
{
public Form1()
{
13
InitializeComponent(); Windows Forms Application,
Classes And Objects, Ui
}
private void Form1_Load(object sender, EventArgs e)
{
private void Registration_Load(object sender, EventArgs e)
{
cn = new SqlConnection(@"Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=H:\Website\Reg
istrationAndLogin\Database.mdf;Integrated Security=True");
cn.Open();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtconfirmpassword.Text != string.Empty || txtpassword.Text !=
string.Empty || txtusername.Text != string.Empty)
{
if (txtpassword.Text == txtconfirmpassword.Text)
{
cmd = new SqlCommand("select * from LoginTable where username='" +
txtusername.Text + "'", cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
cmd.Parameters.AddWithValue("username", txtusername.Text);
cmd.Parameters.AddWithValue("password", txtpassword.Text);
14
Advanced Web Technologies cmd.ExecuteNonQuery();
1.6 INHERITANCE
1.6.1 Inheritance Concepts and working principles:
C# supports inheritance by allowing one class to incorporate another class
into its declaration. This is done by specifying a base class when a derived
class is declared.
15
The following class called TwoDShape stores the width and height of a Windows Forms Application,
Classes And Objects, Ui
twodimensional object, such as a square, rectangle, triangle, and so on.
TwoDShape can be used as a base class (that is, as a starting point) for
classes that describe specific types of two-dimensional objects. For
example, the following program uses TwoDShape to derive a class called
Triangle. Pay close attention to the way that Triangle is declared.
17
Area is 8 Windows Forms Application,
Classes And Objects, Ui
1.7 INTERFACES
In object-oriented programming it is sometimes helpful to define what a
class must do, but not how it will do it. You have already seen an example
of this: the abstract method. An abstract method declares the return type
and signature for a method, but provides no implementation. A derived
class must provide its own implementation of each abstract method
defined by its base class. Thus, an abstract method specifies the interface
to the method, but not the implementation. Although abstract classes and
methods are useful, it is possible to take this concept a step further. In C#,
you can fully separate a class‟ interface from its implementation by using
the keyword interface. Interfaces are syntactically similar to abstract
classes. However, in an interface, no method can include a body. That is,
an interface provides no implementation whatsoever. It specifies what
must be done, but not how. Once an interface is defined, any number of
classes can implement it. Also, one class can implement any number of
interfaces.
To implement an interface, a class must provide bodies for the methods
described by the interface. Each class is free to determine the details of its
own implementation. Thus, two classes might implement the same
interface in different ways, but each class still supports the same set of
methods. Therefore, code that has knowledge of the interface can use
objects of either class since the interface to those objects is the same. By
providing the interface, C# allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism. An interface offers an
alternative to an abstract class for creating contracts among classes and
their clients. These contracts are made manifest using the interface
keyword, which declares a reference type that encapsulates the contract.
An interface is like a class that has only abstract methods.
Interfaces are declared by using the interface keyword. Here is a
simplified form of an interface declaration:
interface interface-name
{
return-type method-name(list of parameters);
}
18
Advanced Web Technologies The interface-name of the interface is specified by name. Methods are
declared using only their return type and signature. They are, essentially,
abstract methods.
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
19
Windows Forms Application,
1.8 ABSTRACT CLASSES Classes And Objects, Ui
20
Advanced Web Technologies class Square: Shape
{
private double side;
public Square( double s)
{
side = s;
}
class Test
{
static void Main(string[] args)
{
Circle c = new Circle(5.0);
Console.WriteLine("Area of Circle = {0}", c.area());
Square s = new Square(2.5);
Console.WriteLine("Area of Square = {0}", s.area());
21
Triangle t = new Triangle(2.0, 5.0); Windows Forms Application,
Classes And Objects, Ui
Console.WriteLine("Area of Triangle = {0}", t.area());
}
}
}
The output of the above program is as follows:
Area of Circle = 78.5
Area of Square = 6.25
Area of Triangle = 5
The abstract class is shape and it contains the abstract method area().
The class Circle is inherited from Shape. It has a private data member
radius. The parameterized constructor assigns a value to radius. The
function area() calculates the area of the circle and returns that value
The class Square inherits from Shape. It has a private data member
side. The parameterized constructor assigns a value to side. The
function area() calculates the area of the square and returns that value.
The class Square inherits from Shape. It has a private data member
side. The parameterized constructor assigns a value to side. The
function area() calculates the area of the square and returns that value.
The class Triangle inherits from Shape. It has private data members
tbase and theight. The parameterized constructor assigns a value to
tbase and theight. The function area() calculates the area of the
triangle and returns that value.
The function main() contains the objects c, s and t for classes Circle,
Square and Triangle respectively. Then the areas of the circle, square
and triangle are printed using the function area().
1.9 SUMMARY
This chapter describes about the C# language which is one of the language
in the .NET framework family. This language supports CLS and CTS. It is
very simple object oriented language which supports interoperability.
C# consists of reserved keywords to use while writing the codes. To do
the decision making if, if.. else, if.. else…if ladder , for loop, while loop,
do—while loop are used with following the defined syntax.
Classes can be complex representations and abstractions of things in the
real world.The structure is of class contains data and function members
The individual instances of class are known as objects. A class has both
properties and behaviors.
22
Advanced Web Technologies The different types of UI controls like textbox, buttons are useful to create
the GUI based environment.
Inheritance concept is used in C# to derive the properties of the base class
to the another class called derived class.
An interface is a contract that guarantees to a client how a class or struct
will behave. When a class implements an interface, it supports the
methods, properties, events, and indexers of the named interface.
An abstract method has no implementation. It creates a method name and
signature that must be implemented in all derived classes.
*****
23
MODULE II
2
INTRODUCTION TO ASP.NET
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Summary
2.3 Unit End Exercises
2.4 List of References
2.0 OBJECTIVES
.NET Framework is a technology that supports building and running
Windows apps and web services. .NET Framework is designed to fulfill
the following objectives:
Provide a consistent, object-oriented programming environment
whether object code is stored and executed locally, executed locally
but web-distributed, or executed remotely.
Provide a code-execution environment that:
o Minimizes software deployment and versioning conflicts.
o Promotes safe execution of code, including code created by an
unknown or semi-trusted third party.
o Eliminates the performance problems of scripted or interpreted
environments.
Make the developer experience consistent across widely varying types
of apps, such as Windows-based apps and Web-based apps.
Build all communication on industry standards to ensure that code
based on .NET Framework integrates with any other code.
2.1 INTRODUCTION
25
6. Next, select the Web Forms template and click the OK button to Introduction to Asp.Net
create the project.
26
Advanced Web Technologies The Visual Studio environment:
27
Introduction to Asp.Net
2.2 SUMMARY
Creating a new ASP.NET Web Forms Page:
When you create a new Web Forms application using the ASP.NET Web
Application project template, Visual Studio adds an ASP.NET page (Web
Forms page) named Default.aspx, as well as several other files and folders.
You can use the Default.aspx page as the home page for your Web
application. However, for this walkthrough, you will create and work with
a new page.
28
Advanced Web Technologies page is blank except for a dashed line that outlines a rectangle. This
rectangle represents a div element on the page.
2. Click inside the rectangle that is outlined by a dashed line.
3. Type Welcome to Visual Web Developer and press ENTER twice.
The following illustration shows the text you typed in Design view.
29
To run the page: Introduction to Asp.Net
30
Advanced Web Technologies This static HTML text is the caption for the TextBox control. You can
mix static HTML and server controls on the same page. The following
illustration shows how the three controls appear in Design view.
Note:
You can display an IntelliSense drop-down list at any time by
pressing CTRL+J when viewing code.
6. Select a color for the Label control's text. Make sure you select a
color that is dark enough to read against a white background.
The ForeColor attribute is completed with the color that you have
selected, including the closing quotation mark.
32
Advanced Web Technologies Programming the Button Control:
For this walkthrough, you will write code that reads the name that the user
enters into the text box and then displays the name in the Label control.
4. Finish the Click event handler for the button so that it reads as shown
in the following code example.
C#Copy
protected void Button1_Click(object sender, System.EventArgs e)
{
33
Label1.Text = TextBox1.Text + ", welcome to Visual Studio!"; Introduction to Asp.Net
}
VBCopy
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
Label1.Text = Textbox1.Text & ", welcome to Visual Studio!"
End Sub
5. Switch back to viewing the Source view of your HTML markup by
right-clicking FirstWebPage.aspx in the Solution Explorer and
selecting View Markup.
6. Scroll to the <asp:Button> element. Note that the <asp:Button>
element now has the attribute onclick="Button1_Click".
This attribute binds the button's Click event to the handler method you
coded in the previous step.
Event handler methods can have any name; the name you see is the
default name created by Visual Studio. The important point is that the
name used for the OnClick attribute in the HTML must match the
name of a method defined in the code-behind.
34
Advanced Web Technologies <asp:Button> control is rendered as the HTML <input
type="submit"> element.
4. Close the browser.
*****
35
3
VARIABLES, DATA TYPES, OPERATORS
AND OBJECTS IN ASP.NET
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Summary
3.3 Unit End Exercises
3.4 List of References
3.0 OBJECTIVES
A web page whose main purpose is to display regular text and images to
the browser is suited for HTML tags only. To make the page more
interesting, you and your users can exchange information, as illustrated in
the previous lesson. For example, you may want your users to submit
values to the server, let the server either store those values or analyze them
and send some results to the user. This interact usually means that, in the
beginning, you would not know the type of value(s) that one visitor would
submit as opposed to another user. Based of this, you must prepare storage
areas on the server's computer memory to temporarily hold the values used
during a visitor's interaction with your web page. This type of storage area
is called a variable.
As there are different types of values used in an application, there are also
different requirements to store those values. Fortunately, to store a value
in a memory, you must provide only two pieces of information: the name
of the variable and the type of information that would be stored in the
memory reserved for that variable.
3.1 INTRODUCTION
The Name of a Variable:
To specify the name of a variable, there are rules you must follow:
The name of a variable must start with either a letter or an underscore. A
name can have only one letter but if you start it with an underscore, then
the underscore must be followed by a letter
After the first character as an underscore or a letter, the name can contain
letters, digits, or underscores in any combination
The name must not contain space but it can be made of various words as
long as these words are concatenated (added together to produce one
word)
36
Advanced Web Technologies The name must not contain any symbol other than letters, digits, or
underscores
After respecting these rules, you can adopt a naming convention that suits
you.
Names in C#:
To name the variables of your program, you must follow strict rules. In
fact, everything else in your application must have a name. C# uses a
series of words, called keywords, for its internal use. This means that you
must avoid naming your objects using one of these keywords. They are:
abstract const extern int out short typeof
As continue false interface override sizeof Uint
base decimal finally internal params stackalloc ulong
bool default fixed is private static unchecked
break delegate float lock protected string unsafe
byte do for long public struct ushort
case double foreach namespace readonly switch using
catch else goto new ref this virtual
char enum if null return throw Void
checked event implicit object sbyte true volatile
class explicit in operator sealed try while
Once you avoid these words, there are rules you must follow when naming
your objects. On this site, here are the rules we will follow:
The name must start with a letter or an underscore
After the first letter or underscore, the name can have letters, digits, and/or
underscores
The name must not have any special characters other than the underscore
The name cannot have a space
Besides these rules, you can also create your own but that abide by the
above. C# is case-sensitive. This means that the names Case, case, and
CASE are completely different.
3.2 SUMMARY
Data Types:
Â
Characters
Escape Sequence Name Description
Makes a sound from
\a Bell (alert)
the computer
\b Backspace Takes the cursor back
Takes the cursor to the
\t Horizontal Tab
next tab stop
37
Takes the cursor to the Variables, Data Types,
Operators And Objects In
\n New line beginning of the next Asp.Net
line
\v Vertical Tab Performs a vertical tab
\f Form feed Â
\r Carriage return Causes a carriage return
Displays a quotation
\" Double Quote
mark (")
Displays an apostrophe
\' Apostrophe
(')
Displays a question
\? Question mark
mark
\\ Backslash Displays a backslash (\)
Displays a null
\0 Null
character
Escape Sequences:
An escape sequence is a special character that displays non-visibly. For
example, you can use this type of character to indicate the end of line, that
is, to ask the program to continue on the next line. An escape sequence is
represented by a backslash character, \, followed by another character or
symbol. For example, the escape sequence that moves to the next line is
\n.
An escape can be included in single-quotes as in '\n'. It can also be
provided in double-quotes as "\n".
The C# language recognizes other escape sequences.
 To use an escape sequence, you can also first declare a char variable
and initialize it with the desired escape sequence in single-quotes.
38
Advanced Web Technologies The Byte Data Type:
A byte is a number whose value can range from 0 to 255 and therefore can
be stored in one byte. You can use it when you know a variable would
hold a relatively small value such as people's age, the number of children
of one mother, etc. To declare a variable that would hold a small natural
number, use the byte keyword. Here is an example:
byte Age;
You can initialize a byte variable when declaring it or afterwards. Here is
an example that uses the byte data type:
Byte Age = 14;
Make sure you do not use a value that is higher than 255 for a byte
variable, you would receive an error. When in doubt, or when you think
that there is a possibility a variable would hold a bigger value, don't use
the byte data type as it doesn't like exceeding the 255 value limit.
Signed Byte:
A byte number is referred to as signed if it can hold a negative of a
positive value that ranges from -128 to 127, which can therefore fit in a
byte. To declare a variable for that kind of value, use the sbyte keyword.
Here is an example:
sbyte RoomTemperature = -88;
Short Integers:
A natural number is also called an integer. To use a variable that would
hold such a number, you can declare it using the short keyword followed
by a name. A variable declared as short can hold a value that ranges from
–32768 to 32767. Here are two examples:
short NumberOfPages;
short Temperature;
NumberOfPages = 842;
Temperature  = -1544;
Because a short integer handles numbers that are larger than the signed
byte, any variable you can declare for a signed byte can also be declared
for a short variable.
NumberOfTracks = 16;
MusicCategory = 2;
To use a variable that would hold quite large numbers, declare it using the
int keyword. A variable declared as int can store values between
–2,147,483,648 and 2,147,484,647 negative or positive. Here is an
example:
int CoordX;
int CoordY;
ÂÂ Â
CoordX = 12;
CoordY = -8;
Unsigned Integers:
If the variable must hold only positive natural numbers, you can declared
it using the uint keyword. The uint keyword is used for a variable that can
hold positive numbers whose value would range from 0 to 2,147,484,647.
Here are examples:
uint DayOfBirth;
uint MonthOfBirth;
uint YearOfBirth;
ÂÂ Â
DayOfBirth  = 8;
MonthOfBirth = 11;
YearOfBirth = 1996;
Long Integers:
To use a variable that can hold very large numbers, declare it using the
long keyword.
Here is an example that uses the long data type:
long CountryArea;
ÂÂ ÂÂÂÂ
CountryArea = 5638648;
Although the long data type is used for large number, it mainly indicates
the amount of space available but you don't have to use the whole space.
For example, you can use the long keyword to declare a variable that
would hold the same range of numbers as the short, the int, or the uint data
40
Advanced Web Technologies types. If you declare a variable as long but use it for small numbers, the
compiler would allocate the appropriate amount of space to accommodate
the values of the variable. Consequently, the amount of space made
available may not be as large as required. If you insist and want the
compiler to reserve the whole space required for a long variable, when
assigning a value to the variable, add an L suffix to it. Here is an example:
long CountryArea;
ÂÂ ÂÂÂÂ
CountryArea = 5638648L;
Keep in mind that an int, a uint, a short, or a ushort can fit in a long
variable.
In some cases, you will need a variable to hold only positive, though large,
numbers. To declare such a variable, you can use the ulong data type. A
variable declared as ulong can handle very large positive numbers that
range from 0 to 18,446,744,073,709,551,615.
A real number is a number that displays a decimal part. This means that
the number can be made of two sections separated by a symbol that is
referred to as the Decimal Separator or Decimal Symbol. This symbol is
different by language, country, group of languages, or group of countries.
In US English, this symbol is the period as can be verified from the
Regional (and Language) Settings of the Control Panel. On both sides of
the Decimal Symbol, digits are used to specify the value of the number.
The number of digits on the right side of the symbol determines how much
precision the number offers.
The integers we have used so far have the main limitation of not allowing
decimal values. C# provides floating values that would solve this problem.
The most fundamental floating variable is declared with the float keyword.
A variable declared a float can store real numbers that range from ±1.5
× 10−45 to ±3.4 × 1038 with a precision of 7 digits in 32 bits.
Here is an example:
float Distance;
When a variable is larger than the float can handle and requires more
precision, you should declare it using the double keyword. A variable
declared as double can store very large numbers ranging from ±5.0 ×
10−324 to ±1.7 × 10308 with a precision of 15 or 16 digits.
41
Variables, Data Types,
Operators And Objects In
Asp.Net
Here is an example:
double StudentAge;
ÂÂ ÂÂÂÂ
StudentAge = 14.50;
Because the double data type provides a better result with a better
precision than the float, whenever you declare a variable as float and
assign it a value as we did earlier, the compiler reserves very large
memory space that can store the values of the variable. If you insist on the
variable being treated as float, when assigning it a value, add an F suffix to
the value. Here is an example:
float Distance;
ÂÂ ÂÂÂÂ
Distance = 248.38F;
Decimal:
The decimal data type can be used to declare a variable that would hold
significantly large values. You declare such a variable using the decimal
keyword. The values stored in a decimal variable can range from ±1.0
× 10−28 to ±7.9 × 1028 with a precision of 28 to 29 digits.
Because of this high level of precision, the decimal data type is suitable
for currency values.
decimal HourlySalary;
ÂÂ ÂÂÂÂ
HourlySalary = 24;
Strings:
42
Advanced Web Technologies Primarily, the value of a string starts with a double quote and ends with a
double-quote. An example of a string is "Welcome to ASP.NET
development".
Sometimes, you will need to use a string whose value is not known in
advance. Therefore, you can first declare a string variable. To do this, use
the string keyword followed by a name for the variable. The name will
follow the rules we defined above. An example of a string declaration is:
string Msg;
To declare a variable that would hold date or time values, use the
DateTime data type. Here is an example:
DateTime DateHired;
The .NET Framework sets its starting periodic date to January 1, 0001 at
midnight (12:00:00 or 0:00 AM). If not assigned a specific value, the
variable is initialized to 1/1/0001 at midnight.
OBJECTS:
The object data type is used to declare a variable whose type is not
primarily defined and can be any of the other data types we have
introduced. Here is an example:
object Whatever;
After creating an object variable, you can use its value as you see fit.
Constants
43
 Variables, Data Types,
Operators And Objects In
Asp.Net
Custom Constants:
Suppose you intend to use a number such as 39.37 over and over again. If
you use this 39.37 many times in your program, at one time, you may
make a mistake and type it as 3937 or 3.937 or else. Because of mistakes
in the way to represent the number, the same calculation produces
different results. To make sure that this is unlikely, you can instead use a
variable that holds the value. Then, when you need that value, you can
access the variable instead of the value itself. A number such as 39.37 is
called a constant.
To create a constant, type the const keyword to its left. When declaring a
constant, you must initialize it with an appropriate value. Here is an
example:
Once a constant has been created and it has been appropriately initialized,
you can use its name where the desired constant would be used. To
initialize a constant variable, the value on the right side of the assignment
operator "=" must be a constant or a value that the compiler can determine
as constant. Instead of using a known constant, you can also assign it
another variable that has already been declared as constant.
Built-in Constants:
There are two main categories of constants you will use in your programs.
You can create your own constant as we saw above. The C# language also
provides various constants. Some constants are part of the C# language.
Some other constants are part of the .NET Framework. Before using a
constant, of course, you must first know that it exists. Second, you must
know how to access it. A constant that is part of the C# language can be
accessed anywhere in your code. Those constant are normally defined in
the System namespace. Other constant are defined in various appropriate
namespaces.
44
Advanced Web Technologies
3.3 UNIT END EXERCISE
*****
45
4
BASIC SERVER-SIDE CONTROL
Unit Structure
4.0 Objectives
4.1 Introduction
4.2 Summary
4.3 Unit End Exercises
4.4 List of References
4.0 OBJECTIVES
Controls are small building blocks of the graphical user interface, which
include text boxes, buttons, check boxes, list boxes, labels, and numerous
other tools. Using these tools, the users can enter data, make selections
and indicate their preferences.
Controls are also used for structural jobs, like validation, data access,
security, creating master pages, and data manipulation.
47
Master pages: These controls provide consistent layout and interface Basic Server-Side Control
throughout the application.
Navigation controls: These controls help in navigation. For example,
menus, tree view etc.
Rich controls: These controls implement special features. For
example, AdRotator, FileUpload, and Calendar control.
The syntax for using server controls is:
4.1 INTRODUCTION
HTML Server controls:
HTML developers must be familiar with old HTML controls, which they
use to write GUI applications in HTML. These controls are the same
HTML controls; you can run these controls on the server by defining the
runat ="server" attribute. These control names start with Html. Below
table defines some of these controls.
CONTROL DESCRIPTION
HtmlForm Create an HTML form control, used as a
place holder of other controls
HtmlInputText Creates an input text box control used to
get input from user
HtmltextArea Creates multiline text box control
HtmlAnchor Creates a Web navigation
HtmlButton Creates a button control
HtmlImage Creates an image control, which is used
to display an image
HtmlInputCheckBox Creates a check box control
HtmlInputRadioButton Creates a radio button control
HtmlTable Creates a table control
HtmlTableRow Creates a row within a table
HtmlTableCell Creates a cell with in a row
48
Advanced Web Technologies Web Server Controls:
Web server controls are more powerful than HTML controls because they
provide more functionality and are easier to use. Besides some of the basic
controls such as button, text box, label, and checkbox, ASP.NET provides
some more powerful controls such as DataGrid, DataList, and Calendar.
I'll use these controls throughout this article. Below table describes some
of these controls.
CONTROL DESCRIPTION
Label Represents a label control
ListBox Represents a list box control
CheckBox Represents a Check box control
Calendar Represents a calendar control
ImageButton Represents an image button control
TableCell Represents a table cell
Panel Represents a panel control
DataList Represents a data list control
TextBox Represents a text box control
Image Represents an image control
CheckBoxList Represents a list box with check boxes
Button Represents a button control
HyperLink Represents a hyperlink control
TableRow Represents a row of a table
RadioButtonList Represents a list box with radio button
controls
DataGrid Represents a data grid control
DropDownList Represents a drop-down list control
AdRotator Represents an ad rotator control
RadioButton Represents a radio button control
LinkButton Represents a link button control
Table Represents a table control
Repeater Represents a repeater control
Validation Controls:
Validating user input is one of the important needs for Web applications.
These controls provide features to validate user input. Using these
controls, you can check as required field, a value, a range, a pattern of
characters, and so on below table describes validation controls.
CONTROL DESCRIPTION
RequiredFieldValidator Makes sure that the user doesn't skip
an entry
CompareValidator Compares user input with a value
using a comparison operator such as
less than, greater than, and so on
49
RangeValidator Checks if the user's input falls with Basic Server-Side Control
in a certain range
RegularExpressionValidator Checks if the user's input matches a
defined pattern
CustomValidator Create your own customer logic
User Controls:
Besides HTML serve controls, web server controls, and validation
controls, you can also create your own controls by embedding Web Forms
controls. These controls are called custom controls. You create custom
controls when the available controls can't provide the functionality you
need. For example, if you want to create a data grid control with check
boxes, combo boxes, calendars, and date controls, you can create a custom
control derived from the available controls and the then write the
additional functionality.
50
Advanced Web Technologies examples in this article. In addition to these classes, it also includes state
management, templates, and validation-related classes.
51
Adding server side controls to a Web Form: Basic Server-Side Control
You have two ways to add server controls to a Web Form (also referred as
a web page). You can either use the VS .NET IDE to add server Controls
or you can add controls manually by typing code using the <asp:> syntax.
52
Advanced Web Technologies ASP.NET version of my first ASP.NET application:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="firstaspnet._Default" %>
<!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:Button ID="Button1" runat="server" Text="Button"
BackColor="#3366FF" Font-Bold="True"
ForeColor="Yellow" /><br />
<br />
<asp:TextBox ID="TextBox1" runat="server"
BorderColor="#66CCFF" BorderStyle="Groove"
Height="32px" Width="198px"></asp:TextBox>
<br />
<asp:ListBox ID="ListBox1" runat="server" BackColor="#CCFF99"
Height="209px" Width="310px">
</asp:ListBox>
<font size="5"><strong>My First ASP.NET
Application</strong></font>
<p>
<font><strong>Click Add button to add contents of text box to the
list box</strong></font>
</p>
</div>
</form>
</body>
</html>
4.2 SUMMARY
53
Most controls include an OnServerEvent for the most commonly used Basic Server-Side Control
event for the control. For example, the <input type=button> control has
an OnServerClick event.
The HTML tags that are not implemented as specific HTML server
controls can still be used on the server side; however, they are added
to the assembly as HtmlGenericControl.
When the ASP.NET page is reposted, the HTML server controls keep
their values.
To use an HTML server control, use the following syntax (which uses
the HtmlInputText control as an example):
ASP.NET (C#)Copy
<input type="text" value="hello world" runat=server />
Web controls are similar to the HTML server controls such as Button,
TextBox, and Hyperlink, except that Web controls have a standardized set
of property names. Web server controls offer the following advantages:
Make it easier for manufacturers and developers to build tools or
applications that automatically generate the user interface.
Simplify the process of creating interactive Web forms, which
requires less knowledge of how HTML controls work and make the
task of using them less prone to errors.
To use a Web server control, use the following syntax (which uses the
TextBox control as an example):
ASP.NET (C#)Copy
<asp:textbox text="hello world" runat=server />
Basic Web controls provide the same functionality as their HTML server
control counterparts. However, basic Web controls include additional
methods, events, and properties against which you can program.
Validation controls
Validation controls are used to validate the values that are entered into
other controls of the page. Validation controls perform client-side
validation, server-side validation, or both, depending on the capabilities of
the browser in which the page is displayed. Validation controls offer the
following advantages:
You can associate one or more validation controls with each control
that you want to validate.
The validation is performed when the page form is submitted.
You can specify programmatically whether validation should occur,
which is useful if you want to provide a cancel button so that the user
can exit without having to fill valid data in all of the fields.
The validation controls automatically detect whether validation
should be performed on the client side or the server side.
List controls
List controls are special Web server controls that support binding to
collections. You can use list controls to display rows of data in a
customized, template's format. All list controls expose DataSource and
DataMember properties, which are used to bind to collections.
List controls can bind only to collections that support the IEnumerable,
ICollection, or IListSource interfaces. For example, a Visual C# .NET
sample page appears as follows:
ASP.NET (C#)Copy
<%@ Page Language="C#" %>
<script runat="server">
Public void Page_Load()
{
String[] myStringArray = new String[] {"one","two","three"};
rptr.DataSource = myStringArray;
rptr.DataBind();
}
</script>
<html>
55
<body> Basic Server-Side Control
56
Advanced Web Technologies The listbox is used to list items available in a store. When the user
clicks on an item in the listbox, its image is displayed in the image
control. When the user clicks the button, the cost of the selected item
is displayed in the control.
*****
57
MODULE III
5
DATABASE PROGRAMMING IN ASP.NET
Unit Structure
5.0 Objectives
5.1 An Overview
5.2 Introduction to ADO.NET
5.3 Architecture of ADO.NET
5.3.1 Connected Architecture
5.3.2 Disconnected Architecture
5.4 Components of ADO.NET
5.4.1 Data Providers
5.4.2 Connection
5.4.2.1 Connection Pooling
5.4.3 Command
5.4.3.1 Working with Stored Procedures with command object
5.4.4 DataSet and Datatable
5.4.5 Data Readers
5.4.6 Data Adapters
5.5 LINQ with ASP.NET
5.5.1 LINQ Introduction
5.5.2 Mapping data model to an Object model
5.5.3 Introducing query syntax
5.5.4 Entity Framework
5.6 Let us Sum Up
5.7 Unit End Exercises
5.8 List of References
Self-Learning Topics: Charts and Data Pagers
5.0 OBJECTIVES
58
Advanced Web Technologies Learn LINQ with ASP.NET.
Discuss about the query syntax in LINQ.
Learn the Entity Framework Architecture.
5.1 AN OVERVIEW
ConnectedArchitecture:
The ADO.NET Connected architecture considers mainly three types of
objects:
▪ Connection con
59
▪ Command cmd Database Programming In
Asp.Net
▪ DataReaderdr
DisconnectedArchitecture:
The ADO.NET Disconnected architecture considers primarily the
following types of objects:
▪ DataSet ds
▪ DataAdapter da
▪ Connection con
Connected Architecture
Disconnected Architecture
Ado.net is both connection-oriented as well as disconnection oriented.
Depending upon the functionality of an application, we can make it
connection-oriented or disconnection oriented. We can even use both the
modes together in a single application.
As the name suggests, connected architecture refers to the fact that the
connection is established for the full time between the database and
application. For e.g. we make a program in C# that is connected with
the database for the full time, so that will be connected architecture.
DataReader is used to retrieve the data from the database and it also
ensures that the connection is maintained for the complete interval of
time.
60
Advanced Web Technologies
In this mode, application issues query then retrieves and store results
for processing. For this purpose, we use objects of DataAdapter and
DataSet classes.
61
Database Programming In
Asp.Net
Connected Disconnected
It is Connection Oriented It is Dis-Connection Oriented
Connected get high in speed and Disconnected get low in speed and
performance. performance.
Connected you need to use a read
Disconnected you cannot
only forward only data reader
Data Reader can’t persist the data Data Set can persist the data
It is Read only, we can’t update
We can update data
the data
62
Advanced Web Technologies 5.4.1 Data Provider:
The Data Provider can also be called a data driver and it can be used as a
major component for your data-driven applications.The functionalities of
the Data Provider are to:
The different data providers are located at the different namespaces, and
these namespaces hold the various data classes that you must import into
your code in order to use those classes in your project.
Table contains the most popular namespaces used by the different data
providers and used by the DataSet.
5.4.2 Connection:
Data Provider contains four sub-classes and the Connection component is
one of them. This class provides a connection between your applications
and the database you selected to connect to your project. To use this class
to setup a connection between your application and the desired database,
you need first to create an instance or an object based on this class.
The Connection object you want to use depends on the type of the data
source you selected. Data Provider provides four different Connection
classes and each one is matched to one different database.
These popular Connection classes used for the different data sources:
The Connection classes and databases
64
Advanced Web Technologies Provider
Data Source
Database
User ID
Password
try
{
conObject.Open();
if (conObject.State == ConnectionState.Open)
Response.Write("Database Connection is Open");
}
catch(SqlExceptionsqlexception)
{
Response.Write("ERROR ::" + sqlexception.Message);
}
catch(Exception ex)
{
Response.Write("ERROR ::"+ex.Message);
}
finally
{
conObject.Close();
}
}
}
In connection string, we can write or Server or Address or Network
Address in place of Data Source attribute. To specify the database we can
use Database or the Initial Catalog attribute.
You can provide yes, no, true, SSPI and false value to Integrated Security
attribute of connection string. If Integrated Security = false then User ID,
and Password must be specified in the connection string and if true then
current Windows account credentials are used for authentication. SSPI is
equivalent to value True.
Connection String
Description
Parameter Name
Identify the server.Local Machine/Machine
Data Source
Domain Name/Ip Address
Initial Catalog Database Name
Integrated Security Set to SSIP to make Connection with user’s
66
Advanced Web Technologies Connection String
Description
Parameter Name
Window Login
UserId Name of user configured in SQL Server
Password Password match Sql Server UserId
Some of the properties for the connection object are as shown below:
Property Description
CanRaiseEvents It gets a value indicating the component can
raise an event
ConnectionString It gets or sets string used to open the
connection
ConnectionTimeout It gets the time to wait for establishing the
connection
Database It gets the name of the current database after
the connection is opened
DataSource It gets the name of the database server to
which the user can connect
Site It gets or sets the ISite of the component
ServerVersion It gets a string representing the version of
the server
State It gets a string that describes the state of the
connection
Some of the methods for the DbConnection object are as shown below:
Methods Description
67
Database Programming In
Open It opens the database connection with the Asp.Net
settings specified by the ConnectionString
object
Output:
Connection String :: Data Source=(local);Initial
Catalog=Employee;Integrated Security=True
DataBase :: Employee
DataSource :: (local)
ConnectionTimeout :: 15
68
Advanced Web Technologies Connection State :: Open
ServerVersion :: 10.50.1600
69
5.4.2.1 Connection Pooling: Database Programming In
Asp.Net
Connection Lifetime:
70
Advanced Web Technologies Connection Reset:
Enlist:
Pooling:
5.4.3 Command:
The Command object works with the Connection object and used to
execute SQL queries or Stored Procedures against the data source. You
can perform insert, update, delete, and select operations with this object. It
requires an instance of a Connection Object for executing the SQL
statements as example.
SqlCommandcmd = new SqlCommand("SQL query or stored
procedure", conn);
The SQL statements can be SELECT, INSERT, UPDATE, or DELETE. It
uses a connection object to perform these actions on the database.
SELECT
cmd =new SqlCommand("select * from Employee", con);
cmd =new OracleCommand("select * from Employee", con);
INSERT
71
cmd = new SqlCommand("INSERT INTO Database Programming In
Asp.Net
Employee(Emp_ID,Emp_Name)VALUES ('" + aa + "','" + bb +"')",con);
cmd = new OracleCommand("INSERT INTO Employee(Emp_ID ,
Emp_Name) VALUES('" + aa + "','" + bb + "' )",con);
UPDATE
cmd =new SqlCommand("UPDATE Employee SET Emp_ID ='" + aa + "'
, Emp_Name ='" + bb + "' WHERE Emp_ID ='" + aa + "'", con);
cmd =new OracleCommand("UPDATE Employee SET Emp_ID ='" + aa
+ "' , Emp_Name ='" + bb + "' WHERE Emp_ID ='" + aa + "'", con);
DELETE
cmd =new SqlCommand("DELETE FROM Employee where Emp_ID='"
+ aa + "'", con);
cmd =new OracleCommand("DELETE FROM Employee where
Emp_ID='" + aa + "'", con);
Create the command object and initialize with SQL query and
connection object.
Execute query with the help of any one method of command object.
Store the result in DataReader object (In case of select SQL query)
Property Description
CommandType.StoredProcedure: It informs
the Command object that the stored procedure
72
Advanced Web Technologies
will be used in place of simple SQL
statements.
Some of the methods for the Command objects are as shown below:
Methods Description
73
Database Programming In
It executes the CommandText against the Asp.Net
Connection object
This method works on select SQL query. It
ExecuteReader() returns the DataReader object. Use
DataReader read () method to retrieve the
rows.
Let’s take one example that will use command object. The table structure
is as follows.
Program:
using System;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlDataReader reader;
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=(local);Initial
Catalog=Employee;Integrated Security=True");
SqlCommandcmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from tblemps";
cmd.CommandType = CommandType.Text;
try
74
Advanced Web Technologies {
con.Open();
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = "ERROR :: " + ex.Message;
}
finally
{
reader.Close();
con.Close();
}
}
}
Stored Procedure:
A stored procedure in SQL Server is a group of one or more SQL
statements. Stored procedure are created and stored in the database.
When you execute the application, the SQL statements are parsed and
execution plan is created. This happened every time whenever you execute
the application.
It is not happened in case of stored procedure. Stored procedure compiles
only once and stores in database with its execution plan. If we use stored
procedure, then we can avoid recompilation of the query. It increases the
performance of application. Another advantage is that it can be tested
independent of the application. Stored procedures are easy to maintain. If
any changes occur, then just update the stored procedure. The change will
reflect in all pages automatically. It is a big advantage that rather than
change SQL queries in all the pages just we need to update a single stored
procedure.
75
CREATE PROCEDURE [dbo].[GetAllEmployees] Database Programming In
Asp.Net
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT * from tblEmps
END
76
Advanced Web Technologies
<configuration>
<connectionStrings>
<add name="conString" connectionString="Data
Source=(local);Initial Catalog=Employee;Integrated Security=True"/>
</connectionStrings>
</configuration>
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
SqlConnectionconObject;
SqlCommandcmd;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string con
=ConfigurationManager.ConnectionStrings["conString"].ConnectionStrin
g;
conObject = new SqlConnection(con);
cmd = new SqlCommand();
cmd.Connection = conObject;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "InsertEmployees";
cmd.Parameters.Add("@EmpID",SqlDbType.Int).Value=txtEmpID.Text;
cmd.Parameters.Add("@EmpName",SqlDbType.VarChar).Value=txtNam
e.Text;
cmd.Parameters.Add("@Gender",
SqlDbType.VarChar).Value=txtGender.Text;
cmd.Parameters.Add("@Salary",
SqlDbType.Money).Value=txtSalary.Text;
cmd.Parameters.Add("@Address",
SqlDbType.VarChar).Value=txtAddress.Text;
77
cmd.Parameters.Add("@DepID", Database Programming In
Asp.Net
SqlDbType.Int).Value=txtDepID.Text;
try
{
conObject.Open();
int i=cmd.ExecuteNonQuery();
if(i>0)
{
Label1.Text = "Record Added Successfully !!";
}
}
catch(Exception ex)
{
Label1.Text="ERROR ::"+ex.Message;
}
finally
{
conObject.Close();
}
}
}
5.4.4 Dataset:
The DataSet class is used for representing a subset of the database. It is
defined in the System.Data namespace. It is used for disconnected
representation of results sets from the Data Source. It provides more
flexibility while dealing with the result sets.
DataSet object behaves like a small database. The DataSet contains rows,
columns, primary keys, constraints, and relation with Data Table objects.
It has a collection of DataTable objects and can be related to each other
with Data Relation objects.
It can contain more than one table and also create the relationship between
tables. Again DataTable is the collection of DataRow and DataColomn
objects.
One of the advantages of dataset is that it can work with different types of
databases simultaneously. Suppose that one table is available within SQL
server and another table is available in Oracle. You can easily query each
database server and create a single DataSet with both the table.
78
Advanced Web Technologies
Property Description
Methods Description
79
Database Programming In
BeginInit It begins the initialization of a DataSet used Asp.Net
on a form or by other component
80
Advanced Web Technologies
Merge(DataRow[]) It merges an array of DataRow objects into
the current DataSet
The DataSet can be used along with the Data Adapter in an application.
The syntax for the creation of DataSet and using in an application is as
shown below:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql,connection);
da.Fill(ds);
Program:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
81
public partial class Default : System.Web.UI.Page Database Programming In
Asp.Net
{
SqlConnection conn;
SqlDataAdapter adapter;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
string cs =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
try
{
conn = new SqlConnection(cs);
adapter = new SqlDataAdapter("select * from tblEmps", conn);
ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch(Exception ex)
{
Label1.Text = "ERROR :: " + ex.Message;
}
finally
{
ds.Dispose();
conn.Dispose();
}
}
}
Property Description
82
Advanced Web Technologies
DisplayExpression It gets or sets the expression returning a value
to represent the table
Methods Description
83
Database Programming In
Merge(DataTable) It merges the DataTable with the current Asp.Net
DataTable
DataColumn dc = newDataColumn();
dc.ColumnName = “Srno”;
dc.DataType = typeof(int);
dt.Columns.Add(dc);
Datarow:
The DataRow is used to represent rows in the DataTable. Some of the
properties of DataRow are as shown below:
Property Description
84
Advanced Web Technologies
Table It gets the DataTable for DataSet
5.4.5 Datareader:
DataReader object works in connected mode. DataReader is used in
forward only, read only retrieval of data from data sources. They cannot
be called directly in the code. It is fast compare to DataSet. DataReader
provides the easy way to access the data from database. It can increase the
performance of application because it reads records one by one. Use read()
method of DataReader to access the record.
readerObj.Close();
85
Database Programming In
Asp.Net
Property Description
Methods Description
Read() Reads next record in the data reader.
Advances the data reader to the next result during
NextResult()
batch transactions.
Close() Closes a DataRaeder object.
You can also get the value of particular column of the table by using the
data reader object.
while(reader.Read())
{
string ID = reader["EmpID"].ToString();
string name = reader["Name"].ToString();
string gender = reader["Gender"].ToString();
string salary = reader["Salary"].ToString();
}
DataSet DataReader
Works in connected mode. It provides connection oriented
environment.
Provides slow performance Provides the fast execution.
compare to DataReader.
In memory object. You can It is a forward-only and read only
fetch the data in any order. object.
Implicitly open the connection. It needs explicit open and close the
connection.
86
Advanced Web Technologies It can contain more than one At a time, it works on single table.
table.
Dataset objects have XML It does not fully support XML
Support.
It uses fill() method of DataReader object provides the
DataAdapter to populate the read() method for reading the
dataset. records.
5.4.6 Dataadapter:
DataAdapter is used as a ADO.NET data provider. It is used in
disconnected architecture. It is used as communication between DataSet
and DataSource. i.e. It works as a bridge between DataSet and your
DataSource. It holds the SQL commands and connection object for
reading and writing data. DataSet does not open or close the connection
because this task is performed by DataAdapter object. It helps to manage
the data in disconnected mode.
DataAdapter performs the following tasks when using with DataSet
object:
1. Open connection
2. Fills the DataSet
3. Close connection
It can also perform Select, Insert, Update and Delete SQL operations with
the database.
The list of DataAdapter properties is as shown below:
Property Description
87
Database Programming In
Methods Description Asp.Net
What is LINQ?
The LINQ (Language Integrated Query) is a part of a language but not a
complete language. It was introduced by Microsoft with .NET Framework
3.5 and C# 3.0 and is available in System.Linq namespace.
LINQ provides us common query syntax which allows us to query the data
from various data sources. That means using a single query we can get or
set the data from various data sources such as SQL Server database, XML
documents, ADO.NET Datasets, and any other in-memory objects such as
Collections, Generics, etc.
88
Advanced Web Technologies
89
LINQ provides a uniform programming model (i.e. common query syntax) Database Programming In
Asp.Net
which allows us to work with different data sources but using a standard
or you can say unified coding style. As a result, we don’t require learning
different syntaxes to query different data sources.
LINQ to Objects:
The LINQ to Objects provider allows us to query an in-memory object
such as an array, collection, and generics types. It provides many built-in
functions that we can use to perform many useful operations such as
filtering, ordering, and grouping with minimum code.
90
Advanced Web Technologies The LINQ to SQL Provider is designed to work with only the SQL Server
database. You can consider this as an object-relational mapping (ORM)
framework which allows one to one mapping between the SQL Server
database and related .NET Classes. These .NET classes are going to be
created automatically by the wizard based on the database table.
LINQ to Datasets:
The LINQ to Datasets provider provides us the flexibility to query data
cached in a Dataset in an easy and faster way. It also allows us to do
further data manipulation operations such as searching, filtering, sorting,
etc. on the Dataset using the LINQ Syntax.
LINQ to Entities:
The LINQ to Entities provider looks like LINQ to SQL. It means it is also
an object-relational mapping (ORM) framework that allows one to one,
one to many, and many to many mapping between the database tables and
.NET Classes. The point that you need to remember is, it is used to query
any database such as SQL Server, Oracle, MySQL, DB2, etc. Now, it is
called ADO.NET Entity Framework.
91
4. LINQ provides a lot of inbuilt methods that we can use to perform Database Programming In
Asp.Net
different operations such as filtering, ordering, grouping, etc. which
makes our work easy.
5. Its query can be reused.
Disadvantages of using LINQ?
The disadvantages of using LINQ are as follows:
1. Using LINQ it’s very difficult to write complex queries like SQL.
2. LINQ doesn’t take the full advantage of SQL features like cached
execution plan for the stored procedure.
3. We will get the worst performance if we don’t write the queries
properly.
4. If we do some changes to our queries, then we need to recompile the
application and need to redeploy the dll to the server.
92
Advanced Web Technologies 5.5.3 Introducing Query Syntax:
LinqTo SQL
Link to SQL is Object Relation Mapping (ORM) framework. It creates the
strongly typed dot net classes based on database tables. LINQ to SQL
enables you to write Select, Insert, Update, Delete query after after
strongly typed dot net classes generated. Behind the seen Link to SQL
provider converts LINQ query to normal SQL query, which is understands
by SQL server database. LINQ to SQL type only supports SQL server
database. It also supports Views, StoredProcedures, and Transactions.
First we will create the database table, name tblEmps in SQL server
as:
You can create the table according to your need and provide the table
name.
Now Right click on the project (or project folder) and select the option
Add New Item.
Select LINQ to SQL Classes Template and Give Name as Emp.dbml. You
can provide the name according to application requirement. Emp.dbml file
will be added under App_Code folder.
Click on Server Explorer and Right click on the Data Connections and
select the option Add Connection.
Add Connection Pop up window will be opened, provide the SQL Server
details and click on OK button.
Database will be added under Data Connections as shown below.
93
Database Programming In
Asp.Net
Drag the table in the left pane. If primary key & foreign key relations are
there then it will automatically displayed. I have not created the foreign
key explicitly. Therefore the relation is not shown.
94
Advanced Web Technologies file name you will provide, it generates the class with class name
appended with DataContext as suffix.
using System;
using System.Collections.Generic;
using System.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(! IsPostBack)
{
LoadData();
}
}
protected void LoadData()
{
EmpDataContextdbContext = new EmpDataContext();
GridView1.DataSource= from emp in dbContext.tblEmps
select emp;
GridView1.DataBind();
}
}
Output:
LINQ have rich set of operators. It provides the operator for Filtering,
Sorting, Grouping, Aggregation, Projection, Partitioning, Concatenation
etc.
You can use any operators with the LINQ to get the result.
You can create a projection that matches the employee object structure. In
the above query it selects all the records. If you want that few column
should be display, then you can use linq query as
fromemp in dbContext.tblEmps
select new{emp.EmpID , emp.Name};
95
Controlling column ordering and column name using LINQ: Database Programming In
Asp.Net
LINQ enables you to change the order of column for display. You can also
provide the custom name for column.
fromemp in dbContext.tblEmps
select new {
DepartmentID=emp.DEPID,EmployeeID=emp.EmpID,EmpName=emp.N
ame };
Query filters:
LINQ provides the where clause to filter the query.
Suppose that you want the record of those employees whose name is starts
with letter “R” and salary greater than 20000.
fromemp in dbContext.tblEmps
where emp.Name.StartsWith("D") &&emp.Salary>20000
select emp;
96
Advanced Web Technologies dbContext.tblEmps.InsertOnSubmit(empObj);
dbContext.SubmitChanges();
}
GetData();
}
97
btnInsert_Click method will be executed and record is added in the Database Programming In
Asp.Net
database.
First Method:
You can use the log property of DataContest class. It writes the generated
sql query at provided I/O.
dbContext.Log = Response.Output;
Second Method:
You can directly use the ToString() method as:
Response.Write(selectQuery.ToString());
98
Advanced Web Technologies Third Method:
GetCommand method of DataContext class provides the information
about sql command generated by LINQ to SQL.
stringsqlQuery=dbContext.GetCommand(selectQuery).CommandText;
Response.Write(sqlQuery);
99
execute the relevant query in the database and then materialize results into Database Programming In
Asp.Net
instances of your domain objects for you to work within your app.
It is platform independent.
It keeps the track of values that have been changed of the properties
of entities.
100
Advanced Web Technologies It also allows configuring the EF Model by a fluent API to override
the default convention.
If you made any changes in database schema then you can reflect
those changes in EF model by writing migration command in CLI
(Command Line Interface).
101
Database Programming In
5.8 LIST OF REFERENCES Asp.Net
*****
102
6
DATABOUND CONTROLS IN ASP.NET
Unit Structure
6.0 Objectives
6.1 An Overview
6.2 SqlDataSource control
6.3 Databound Controls
6.3.1 DataList
6.3.2 DetailsView
6.3.3 FormView
6.3.4 GridView
6.3.5 ListView
6.3.6 Repeater
6.4 Let us Sum Up
6.5 Unit End Exercises
6.6 List of References
Self-Learning Topics: Charts and Data Pagers
6.0 OBJECTIVES
What You Will Learn in This Chapter:
Learn about how to bind data to data bind control
- DataList
- DetailsView
- FormView
- GridView
- ListView
- Repeater
6.1 AN OVERVIEW
Databound controls are used to display data to the end-user within the web
applications and using databound controls allows you to manipulate the
data within the web applications very easily.
Databound controls are bound to the DataSource property. Databound
controls are composite controls that combine other ASP.NET Controls like
Text boxes, Radio buttons, Buttons and so on.
103
Databound Controls In
6.2 SQLDATASOURCE CONTROL Asp.Net
105
<head runat=”server”> Databound Controls In
Asp.Net
<title></title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:DataList ID=”DataList1” runat=”server”
DataKeyField=”Id” DataSourceID=”SqlDataSource1”
Height=”285px” RepeatColumns=”3”
RepeatDirection=”Horizontal” Width=”134px”>
<ItemTemplate>
Id:
<asp:Label ID=”IdLabel” runat=”server” Text=’<%# Eval ( “Id”
)%>’ />
<br/>
name:
<asp:Label ID=”nameLabel” runat=”server” Text=’<%# Eval (
“name” )%>’ />
<br/>
Income:
<asp:Label ID=”IncomeLabel” runat=”server” Text=’<%# Eval (
“Income” )%>’ />
<br/>
<br/>
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID=”SqlDataSource1” runat=”server”
ConnectionString=’<%$ConnectionStrings:ConnectionString %>”
SelectCommand=”SELECT * FROM [footerex]”>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Output is:
106
Advanced Web Technologies Property Description
AllowPaging It is a Boolean value to indicate the
control supports navigation
DataSource It is used to populate the control with the
data source object
DataSourceID It indicates the bound data source control
with corresponding adapters
AutoGenerateEditButton It is a Boolean value to indicate the
column can be edited by the user
AutoGenerateDeleteButton It is a Boolean value to indicate the
records can be deleted
DefaultMode It is used to indicate the default display
mode of the control
AutoGenerateRows It is a Boolean value to indicate the rows
are automatically created for each field in
the data source
The sample code for the Details View control is as shown below:
<%@ Page Language=”C#” %>
<script runat=”server”>
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>asp.net DetailsView example: how to use
DetailsView</title>
</head>
<body>
<form id=”form1” runat=”server” >
<div>
<h2 style=”color:Navy” >DetailsView Example</h2>
<asp:SqlDataSource ID=”SqlDataSource1” runat=”server”
ConnectionString=”<%$ ConnectionStrings:
NorthwindConnectionString %>”
Select Command = “SELECT ProductID, ProductName,
UnitPrice FROM Products”;
</asp:SqlDataSource>
<asp:DetailsView ID=”DetailsView” runat=”server”
DataSourceID=”SqlDataSource1” AllowPaging=”true”
ForeColor=”DarkGreen” BackColor=”Snow”
107
BorderColor=”Tomato”> Databound Controls In
Asp.Net
</asp:DetailsView>
</div>
</form>
</body>
</html>
Property Description
EditItemTemplate It is used when the record is being edited by
the user
InsertItemTemplate It is used when a record is being created by
the user
ItemTemplate It is the template used to render the record to
display only in an application
Methods Description
InsertItem It is used to insert record in the database
UpdateItem It is used to update record in the database
DeleteItem It is used to delete the record in the database
ChangeMode It is used to change the working state of the control
109
Output is: Databound Controls In
Asp.Net
Property Description
AllowPaging It is a Boolean value indicating the
control supports paging
AllowSorting It is a Boolean value indicating the
control supports sorting
SortExpression It accepts the current expression
determining the order of the row
Datasource It is used to get or set the data source
object containing the data to populate
the control
AutoGenerateEditButton It is a Boolean value indicating that the
user can edit the record in the control
DataSourceID It indicates the data source control to
be used
AutoGenerateDeleteButton It is a Boolean value indicating that the
user can delete the record in the control
AutoGenerateColumns It is a Boolean value to indicate the
columns are automatically created for
each field of the data source
AutoGenerateSelectButton It is a Boolean value to indicate the
column should be added to select the
particular record
SortDirection It gets the sorting direction of the
column for the control
EmptyDataText It indicates the text to appear when
there is no record in the data source
110
Advanced Web Technologies The code sample of the GridView control is as shown below:
1) Add a new connection object to the ASP.NET web application as
shown below:
2) Next, add a new table for the connection object created above. The
snippet for adding the table is as shown below:
3) Add the fields Sno, Name, Address in the table. Add values to the
respective fields in the table
4) Add the GridView and SqlDataSource control to the design view of
the web page.
111
5) The source code for the GridView control is as shown below: Databound Controls In
Asp.Net
112
Advanced Web Technologies 6.3.5 Listview Control:
The ListView control is used to bind to data items returned to the data
source and display them. The control displays data in a format defined by
using templates and styles. The list of templates supported by the control
are as shown below:
Templates Description
ItemTemplate It identifies the data bound content to
display for single items
ItemSeperatorTemplate It identifies the content to be rendered
between the items
LayoutTemplate It identifies the root template that defines
the main layout
GroupTemplate It identifies the content of the group
layout
GroupSeperatorTemplate It identifies the content to be rendered
between the group of items
EmptyItemTemplate
It identifies the control to render for an
empty item when the GroupTemplate is
used
EmptyDataTemplate It identifies the content to render if the
data source returns no data
SelectedItemTemplate It identifies the content to render for the
selected data item to differentiate the
selected item from the other displayed
items
EditItemTemplate It identifies the content to render when the
item is lost
InsertItemTemplate It identifies the content to render when an
item is being inserted
113
.TableHeader Databound Controls In
Asp.Net
{
background-color:OrangeRed;
color:snow;
font-size:large;
font-family:Verdana;
}
.TableData
{
Background-color:Orange;
color:Snow;
font-family:Courier New;
font-size: medium;
font-weight:bold;
}
</style>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<h2 style=”color:Navy; font-style:italic;”>ListView Control Example:
How to Use ListView Control</h2>
<hr width=”550” align=”left” color=”PowderBlue” />
<asp:SqlDataSource ID=”SqlDataSource1” runat=”server”
ConnectionString=”<%$ConnectionStrings:NorthwindConnectionString”
%>”
SelectCommand = “Select ProductID, ProductName From products
Order By ProductId”
>
</asp:SqlDataSource>
<br/>
<asp:ListView ID=”ListView1” runat=”server”
DataSourceID=”SqlDataSource1” >
<LayoutTemplate>
<table runat=”server” class=”TableCSS”>
<tr runat=”server” class=”TableHeader”>
<td runat=”server”>ProductID</td>
<td runat=”server”>ProductName</td>
</tr>
<tr id=”ItemPlaceHolder” runat=”server”>
<tr runat=”server”>
<td runat=”server” colspan=”2”>
<asp:DataPager ID=”DataPager1” runat=”server”>
<Fields>
<asp:NextPreviousPageField ButtonType=”Link” />
</Fields>
</asp:DataPager>
</td>
</tr>
114
Advanced Web Technologies </table>
</LayoutTemplate>
<ItemTemplate>
<tr class=”TableData” >
<td>
<asp:Label ID=”Label1” runat=”server”
Text=’<%#Eval(“ProductID”)%>’>
</asp:Label>
</td>
<td>
<asp:Label ID=”Label2” runat=”server” Text=’<%#Eval
(“ProductName”)%>’>
</asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
</div>
</form>
</body>
Output is:
115
The sample code for the Repeater control is as shown below: Databound Controls In
Asp.Net
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Repeater ID=”RepeaterInformation” runat=”server”>
<HeaderTemplate>
<table class=”tblcolor”>
<tr>
<b>
<td>
Roll No
</td>
<td>
StudentName
</td>
<td>
Total Fees
</td>
</b>
</HeaderTemplate>
</ItemTemplate>
<tr class=”tblrowcolor”>
<td>
<%#DataBinder.Eval ( Contiane.”DataItem.RollNo”)%>
</td>
<td>
<%#DataBinder.Eval(Contianer,”DataItem.Name”)%>
</td>
<td>
<%#DataBinder.Eval(Contianer.”DataItem.Fees”)%>
</td>
</tr>
</ItemTemplate>
<SeperatorTemplate>
<tr>
<td>
<hr/>
</td>
<td>
<hr/>
</td>
<td>
<hr/>
</td>
</tr>
</SeperatorTemplate>
<FooterTemplate>
<tr>
<td>
116
Advanced Web Technologies School Records displayed
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
The code behind file is as shown below:
public partial class _Default: System.Web.UI.Page
{
SqlConnection con;
SqlCommand cmd = new SqlCommand();
protected void Page_Load( object sender, EventArgs e)
{
con=new SqlConnection(
ConfigurationManager.ConnectionStrings[“constr”].ConnectionString);
cmd.Connection=con;
com.Open();
RepeatInformation.DataSource = cmd.ExecuteReader();
RepeatInformation.DataBind();
con.Close();
}
}
Output is:
117
2. Define: Databound Controls In
Asp.Net
a. DataList
b. DetailsView
c. FormView
d. GridView
e. ListView
f. Repeater
3. Explain DataList in detail?
4. Explain DetailView in detail?
5. Explain FormView in detail?
6. Explain GridView with example?
7. Explain ListView with example?
8. Explain Repeater in detail?
*****
118
MODULE IV
7
SESSION MANAGEMENT
Unit Structure
7.0 Objective
7.1 Introduction
7.2 State Management
7.2.1.Client-Side state management
7.2.1.1. View state
7.2.1.2. QueryString
7.2.1.3. Coockie
7.2.1.4. Hidden Field
7.2.2 Server-Side state management
7.2.2.1. Session state
7.2.2.2 Application State
7.2.2.3 Cache
7.2.2.4 Profiles
7.3 Summary
7.4 Unit End Exercises
7.5 List of References
7.0 OBJECTIVE
In this chapter we learned sate management and its types i.e client side
state management and server-side state management.
We learned also View state,querystring Cookie, how to be hidden field in
the Client-Side state management.
7.1 INTRODUCTION
Microsoft frameworks are strongly taken into consideration for their
security capabilities. Some of the surprising functions include
authentication-authorization control, HTTPS enforcement, error
management with Global Exception Handling support in ASP.NET Core,
CORS control, etc.
Talking about HTTP, that is this kind of protocol that doesn't have a
status. Therefore, if we want to transfer statistics from one page to some
other page or even after numerous visits to the identical page, we have to
119
use country control techniques. Today, we're going to research kingdom Session Management
control techniques the usage of ASP.NET.
State Management is the procedure in which developers can keep repute
and web page data on more than one requests for the identical or
extraordinary pages in the net application.
120
Advanced Web Technologies The main benefit of getting this form of state management is that it saves a
tremendous amount of server reminiscence. We reduce the load on the
server to preserve state information.
Due to the increased bandwidth, it reduced speed of loading and creating
security issue for confidential data such as credit card number, password.
In the web application .NET is support following types of methods in the
client-side state management:
7.2.1.1 View State
7.2.1.2 Query String
7.2.1.3 Cookie
7.2.1.4 Hidden field
121
3. <!DOCTYPE html PUBLIC "- Session Management
5. <head runat="server">
6. <title></title>
7. </head>
8. <body>
9. <form id="form1" runat="server">
10. <div>
11. User Name:-
<asp:textbox id="TextBox1" runat="server"><
/asp:textbox>
12. <br />
13. Password :-
<asp:textbox id="TextBox2" runat="server"><
/asp:textbox>
14. <br />
15. <asp:button id="Button1" runat="s
erver" onclick="Button1_Click" text="Submit
" />
16. <asp:button id="Button3" runat="s
erver" onclick="Button3_Click" text="Restor
e" />
17. </div>
18. </form>
19. </body>
20. </html>
123
7.2.1.3. Cookie: Session Management
1. Persistent cookie:
The persistent cookie permanently stored on hard drive of user.
Persistent cookie has expiry date time. This type of cookie permanently
stored user hard drive till date time we set.
For example: Response.Cookies[“Name”].Value=”IDOL”;
Response.Cookies[“IDOL”].Expires=DateTime.Now.AddM
inutes(30);
Using following syntax, we create Cookie:
HttpCookie strname= new HttpCookie(“name”);
Strname.Value=”IDOL”;
Strname.Expires=DateTime.Naow. AddMinutes(30);
Here, Response.Cookies is use to create the Cookie and 30 minutes is
expiry time after 30 Minutes cookies will expire.
Syntax of session:
Session[“session_name”]=”Session value”;
Declare session:
Session[“name”]=”IDOL”;
Response.Redirect(“nextpage.aspx”);
125
To retrive the session value: Session Management
String myvalue=session[“name”].Tostring();
Response.Write(“Name=”+myvalue);
Mechanism of session Managements are:
1. In Proc mode
2. Out Proc mode
A. Sql Server
B. State Server
126
Advanced Web Technologies 5. Application_End
6. Application_Disposed()
7.2.2.3 Cache:
To enhanced website performance caching features does helps. The cache
can store any data object, pages they can store in the memory, when first
time requested. User can store or cache data object, pages on the other
software or web server in the request stream for example browser or proxy
server. By allowing commonly requested content to be temporarily stored
faster way it is improving server performance.
7.2.2.4 Profile:
As the applications must have to manage the users’ unique details or
information such as last date of visited, require query or enquiry. The
ASP.NET features helps to find or recognised users based unique identy.
Its profile features associate’s information with an individual user and
stores the information in a persistent format.
Syntax:
<profile>
<properties>
<add name=”LastDateOfVisit”>
<add name=”enquiry”>
<add name=”LastQuery”>
</properties>
</profile>
7.3 SUMMARY
In this chapter we learned some state management mechanism using
ASP.NET MVC. It will help us to understand various method used for
enhancing it and provide an idea about state management.
127
2. What is Cache explain it with an example. Session Management
*****
128
8
AJAX
Unit structure
8.0 Objective
8.1 What is Ajax?
8.2 Application with Ajax.
8.3 AJAX Controls
8.4 Testing an ASP.NET Ajax application
8.5 Global.asax and Web Config
8.6 Summary
8.7 Unit End Exercises
8.8 List of References
8.0 OBJECTIVE
In this chapter we will learned:
1. What is AJAX? Why we need AJAX.
2. How we can create AJAX application.
3. Controls of the AJAX
4. Testing an ASP.NET Ajax application
5. Global.asax and Web Config
</script>
< script src=”~/Scripts/jquery.unobtrusive-ajax.min.js”
type=”text/javascript”>
</script>
{
Public class User
{
Public int UserId{ get;set;}
Public string firstName{get;set}
Public string LastName{get;set}
Public D ateTime Birthdate{ get; set}
Pubic Role Role { get, set}
}
Public enum Role {
Admin
Employee
Guest
}
}
130
Advanced Web Technologies How the Ajax works?:
Client Server
Request(.aspx)
Html and CSS .NET CODE
Send page
Scripting language Web services
XMLHttpRequest
ASP.NET AJAX Framwork ASP.NET AJAX Framework
Send XML
1. UpdatePanel:
The UpdatePanel control specifies a part of a Web page which can be
updated or refreshed partially based on the update condition. Refreshing a
specific part of a Web page is referred as partial-page update. You can
also add one or more UpdatePanel control in the Web page. The
UpdatePanel control uses the AJAX library to support the partial-page
rendering.
It is a container control that contain the all controls and that control define
the region or branch which is capable of making page updates.
For example:
<form Id=”form1” runat=”server”>
<asp:ScriptManager ID=”MainScriptManager” runat=”server”/>
<asp:UpdatePanel ID=”pnlWelcome” Text=”Click the button”/>
<ContentTemplate>
<asp:Lable runat=”server” ID=”btnWelcome”
OnClick=”btnwlcome_Click” Text=”Upadate lable!” />
</ContentTemplate>
</asp:UpdatePanel>
</form>
.
131
2. ScriptManager Control: Ajax
3. ScriptManagerProxy control:
A web page will have handiest one ScriptManager control. If your
software has a Master-Content page state of affairs and the MasterPage
has a ScriptManager control, then you may use the ScriptManagerProxy
control to feature distinctive scripts to the content material pages.
Sometimes, there can be the case when you aren't required to apply AJAX
on every and each net page by way of using the ScriptManagerProxy
control then you can add AJAX functionalities to precise net pages. Since,
ScriptManager at the Master Page will load the AJAX library on every
web page that derives from the MasterPage, although they're now not
wished, which would lead to a waste of resources.
Example:
<asp:Update ID=”UpdatePanel1” runat=”server”>
<Content Template>
<asp:GridView ID=”GridView1” runat=”server”>
</asp:GridView>
<asp:UpdateProgress ID=”UpdateProgress1” runat=”server”>
<ProgressTemplate>
<div style=”font-size:large”>Processing…..</div>
</ProgressTemplate>
</asp:updateProgress>
132
Advanced Web Technologies </ContentTemplate>
</asp:UpdatePanel>
5. Timer:
Timer Control is used to perform postbacks at defined time intervals. You
can also use the Timer control with an UpdatePanel control to enable
partial-page updates at a defined interval. You can also use the Timer
control to post the entire page.
Timer is an Ajax control that can be used to update portion of page on
periodic, time basis. You can use if you want to update an image such as
on webpage advertisement or stock ticker/news ticker. It is add the code a
timer control directly to an UpdatePanel control.
Example:
<asp:Update ID=”UpdatePanel1” runat=”server”>
<Content Template>
<asp:Image ID=”Image1” runat=”server”
ImageUrl=”~/images/contoso.png”/>
<asp:Timer ID=”Timer1” runat=”server” Interval=”7000”
ontick=”timer1_Tick”>
</asp:Tomer>
</ContentTemplate>
</asp:UpdatePanel>
133
Reference: Testing of ASP.NET Applications (loadtestingtool.com) Ajax
134
Advanced Web Technologies Note that the Module for ASP.NET Testing is optional. It facilitates the
design of your profiles and reduces the amount of manual work required to
test an ASP.NET site. If you are not sure about the necessity to use it in
your case, you can try the following steps.
1. After recording a virtual user profile, verify it using the "Verify Test"
button on the toolbar.
2. Take a look at the created logs. You can find them in the "Logs"
folder in the left view. If you see errors occurred during the
verification, especially 500 (internal server error), 501 or similar ones,
it means that profiles have been parameterized incorrectly. In this case
you can either install the Module for ASP.NET Testing, or try to
parameterize your profiles manually using regular WAPT functions
available without the module.
8.6 SUMMARY
From this chapter we have learned Ajax features in MVC. The key to
success with Ajax in ASP.NET MVC 5 is in understanding jQuery and
making jQuery work for you in your application. Not only is jQuery
flexible and powerful, but it also allows you to separate your script code
from your markup and write unobtrusive JavaScript. The separation means
you can focus on writing better JavaScript code and embracing all the
power jQuery has to offer.
135
Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wrox Press, Ajax
*****
136
MODULE V
9
WEB SERVICES AND WCF
Unit Structure
9.0 Objectives
9.1 Introduction
9.2 Web Service
9.2.1 Advantages of Web Services
9.2.2 Disadvantage of Web Services
9.2.3. Examples of web services
9.2.4 Creating and Consuming an XML WCF Service-Simple and
Database
9.2.5 WCF Features
9.2.6 Advantages of WCF
9.2.7 Examples of WCF Service
9.3 Summary
9.4 Unit End Exercises
9.5 List of References
9.0 OBJECTIVE
From this chapter you under:
● What is mean by Web Service.
● What web service can do and cannot do.
● Identity the key components or technologies involved in web services.
● Identify who manages the web services specification.
● Examine the examples of the web services.
● Impart understanding of Web Techniques and Design Web Services.
9.1 INTRODUCTION
Web services developed by Microsoft in June 2000, Web services as a key
component of its .Net initiative, a broad vision for embracing the Internet
in the development, engineering, and use of software. Web Services is
nothing but software program by using this you can communicating your
web application. Web services are web application components. Web
Service means to interact with the objects over the internet. It is
functionality use in different platforms using protocols.
137
● It does not dependants on any language you can we can write web Web Services And Wcf
services in any language and access the same using any other
language.
● It is protocol independent.
● It is platform independent.
● It is self-contained and self-describing.
● It is stateless architecture.
● HTTP and XML open and text-based are the basis for web services.
Syntax:
1. It is case sensitive.
2. first statement must be XML document
138
Advanced Web Technologies 3. HTTP protocol is used for overriding the value of encoding.
Whenever we use web services there are two ways to use web services:
1. Reusable application components.
2. Connect the existing software.
139
9.2.3 Examples of web services: Web Services And Wcf
Step 1: Open visual studio (version -2017) in menu create new project.
Step 2: New windows appears then you have to select web in left part and
in the right parts you have to select ASP .Net Web Application (.Net
Framework)
140
Advanced Web Technologies Step 3: Select Web Application as Empty and web form.
Step 4: Right side windows you can see the name of Web applications
select add the new items.
141
Step 5: We have created one method that is add () Web Services And Wcf
142
Advanced Web Technologies Step 7: You can see method add ()
Step 8: When you click on add () method, you have to put the values of
parameters.
143
9.2.4 Creating and Consuming an XML WCF Service-Simple and Web Services And Wcf
Database:
WCF means Windows Communication Foundation. It is a framework for
building, configuring, and deploying network-distributed services. Firstly,
its Indigo, which enables hosting services in any type of operating system
process. WCF is a service-oriented application. Using WCF we can build
connected secure, reliable, transacted solutions that integrate across
platforms.
It is a framework for building service-oriented applications. Data can be
sent as asynchronous messages from one service to another.
A client is an application which uses WCF client to communicate with
services or other clients.
WCF Hosting:
Web services that was hosted inside web server such as IIS using http or
Https protocols.
1. IIS
144
Advanced Web Technologies 2. WAS (Windows process activation services)
3. Self-hosting
4. Windows service
145
9.2.7 Examples of WCF Service: Web Services And Wcf
Step 1: For WCF service while creating new project under visual C#
select WCF (Window-1) and choose WCF service application as we must
apply WCF service (Window-2) then press ok with your WCF service
name.
146
Advanced Web Technologies Step 2: Check interface in solution Explorer that is (IService.cs). Here we
have GetData() Method so we have to make entry in interface service after
that execute your program by clicking on IIS Express (Internet Explorer)
147
Web Services And Wcf
148
Advanced Web Technologies
Step 5: Execute the program and put the values of a and b and press the
button invoke. It display addition of two numbers.
9.3 SUMMARY
Web Services is nothing but software program by using this you can
communicating your web application. Web services are web application
components. Web service types of Reusable application components XML
(Extensible Markup Language), SOAP (Simple Object Access Protocol),
WSDL (Web Services Description Languages) and UDDI (University
Description, Discovery, and Integration) WCF means Windows
Communication Foundation. It is a framework for building, configuring,
and deploying network-distributed services. We can apply web service and
WCF services.
Self-Learning Topics:
Caching Web service responses
149
Web Services And Wcf
9.4 UNIT END EXERCISES
1. What is web service. Explain Example of web service.
2. Explain WCF in details.
3. Explain Advantages of Web Service.
4. Explain Features of WCF.
5. Explain how to start WCF with example.
6. Design Web Application to produce and Consume a WCF Service.
7. Design Web Application to produce and consume a web Service.
*****
150
MODULE VI
10
DESIGNING MVC APPLICATION
Unit Structure
10.0 Objective
10.1 Introduction
10.2 Designing MVC application
10.2.1 First application of MVC:
10.2.2 Creating new ASP.NET MVC Project
10.3 Creating a Simple Data-Entry Application with validations
10.3.1 Designing a Data Model
10.3.2 Linking action Method
10.3.3 Creating Action Method
10.4 Using Automatically Implemented Properties
10.5 Using Object and Collection Initializers
10.6 Using Extension Methods
10.7 Using Lambda Expressions
10.8 Programs based on MVC Pattern
10.9 Forms and HTML Helpers
10.10 Define and access the model type
10.11 Summary
10.12 Unit End Exercises
10.13 List of References
10.0 OBJECTIVE
In this chapter we will learn how to create and design MVC application
using multiple patterns, methods and expressions.
Why we need it?
10.1 INTRODUCTION
USE
R
Controll
er
Communica
tion Modificati
Presentati on
on
Updates
View Mod
Presentatio el
nnn
Figure 1
152
Advanced Web Technologies 10.2 DESIGNING MVC APPLICATION
153
Designing Mvc Application
154
Advanced Web Technologies We can try to run the application now by selecting Start Debugging from
the Debug menu.
We can see the result in below fig Because when we started with the
empty project template, the application does not contain anything to run,
so the server generates a 404 Not Found Error.
155
folder in the project and select Add -�Controller. Please Name this Designing Mvc Application
Controller and click Add.
156
Advanced Web Technologies name: names given to controllers should indicate their purpose; the default
controller is called Home and controller names have the suffix Controller.
157
HomeController.cs file so that it matches Listing 2. We have highlighted Designing Mvc Application
the statements that have changed so they are easier to see.
Listing 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PartyInvites.Controllers
{
public class HomeController: Controller
{
public string Index()
{
return "Hello World";
}
}
}
We have changed the action method called Index so that it returns the
string “Hello World”. Run the project again by selecting Start Debugging
from the Visual Studio Debug menu. The browser will display the result
of the Index action method, as shown in following fig 1.9
Just Imagine Client has to host new year party and has to ask us to create
web application that allows to invitees to electronic RSVP and ask
following key features
1. A home page that shows information about the party
2. A form that can be used to RSVP
158
Advanced Web Technologies 3. Validation for the RSVP form, which will display a thank-you page
4. RSVPs e-mailed to the party host when complete
In the following sections, we will build up the MVC project we created at
the start of the chapter and add these features. We can check the first item
off the list by applying what we covered earlier and add some HTML to
my existing view to give details of the party. Listing 3.1 shows the
additions we made to the Views/Home/Index.cshtml file.
Listing 3.1
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Greeting World (from the view)
<p>We're going to have an exciting party.<br/>
(To do: sell it better. Add pictures or something.)
</p>
</div>
</body>
</html>
We are on our way. If you run the application, you’ll see the details of the
party—well, the placeholder for the details, but you get the idea—as
shown in following fig 11
159
10.3.1 Designing A Data Model: Designing Mvc Application
In MVC, the M stands for version, and it's far the most essential a part of
the software. The model is the illustration of the real global items,
techniques, and policies that define the problem, called the area, of the
utility. The version, frequently called a website model, consists of the C#
objects (referred to as domain items) that make up the universe of the
utility and the techniques that manage them. The perspectives and
controllers expose the domain to the clients in a steady manner and a well-
designed MVC software starts with a well-designed model, that's then the
focus as controllers and perspectives are delivered.
We don’t need a complicated model for the PartyInvites application
because it's miles this type of easy software and we need to create simply
one domain class which I will call GuestResponse.
This object will be chargeable for storing, validating, and confirming an
RSVP.
The MVC convention is that the classes that make up a model are placed
inside the Models folder, which Visual Studio created as part of the initial
project setup. Right-click Models in the Solution Explorer window and
select Add followed by Class from the pop-up menus.
Set the file name to GuestResponse.cs and click the Add button to create
the class. Edit the contents of the class to match Listing 3.2
If you don’t have a Class menu item, then you probably left the Visual
Studio debugger running. Visual Studio restricts the changes you can
make to a project while it is running the application.
Listing 3.2 The GuestResponse Domain Class Defined in the
GuestResponse.cs File
namespace PartyInvites.Models
{
public class GuestResponse
{
public string Name {get; set;}
public string Email {get; set;}
public string Phone {get; set;}
public bool? WillAttend {get; set;}
}
}
160
Advanced Web Technologies shown in Listing 3.3.
Adding a Link to the RSVP Form in the Index.cshtml File
@{
Layout = null;
}<
!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Greeting World (from the view)
<p>We're going to have an exciting party.<br />
(To do: sell it better. Add pictures or something.)
</p>
@Html.ActionLink("RSVP Now", "RsvpForm")
</div>
</body>
</html>
Html.ActionLink is an HTML helper method. The MVC Framework
comes with a collection of built-in helper methods that are convenient for
rendering HTML links, text inputs, checkboxes, selections, and other
kinds of content. The ActionLink method takes two parameters: the first is
the text to display in the link, and the second is the action to perform when
the user clicks the link. I explain the complete set of HTML helper
methods in next point. We can see the link that the helper creates by
starting the project, as shown in figure12
You will see a 404 Not Found error if you click the link. That’s because
we have not yet created the action method that corresponds to the
/Home/RsvpForm URL. we do this by adding a method called RsvpForm
to the HomeController class, as shown in Listing 3.4
Listing 3.4
Adding a New Action Method in the HomeController.cs File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PartyInvites.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
int hour = DateTime.Now.Hour;
ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good
Afternoon";
return View();
}
public ViewResult RsvpForm()
{
return View();
}
}
}
To add a view for the RsvpForm action method, but in a slightly different
way—we need to create a stronglytyped view.
A strongly typed view is intended to render a specific domain type, and if
I specify the type I want to work with
(GuestResponse in this case), MVC can create some helpful shortcuts to
make it easier.
162
Advanced Web Technologies Right-click the RsvpForm method in the code editor and select Add View
from the pop-up menu to open the AddView dialog window. Ensure that
the View Name is set as RsvpForm, set Template to Empty and select
GuestResponse from the drop-down list for the Model Class field. Leave
the View Options boxes unchecked, as shown in figure 13
163
<div> Designing Mvc Application
</div>
</body>
</html>
Building Form:
Now that we have created the strongly typed view, we can build out the
contents of RsvpForm.cshtml to make it into an HTML form for editing
GuestResponse objects, as shown in
Listing 3.6
Creating a Form View in the RsvpForm.cshtml File
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}<
!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
</head>
<body>
@using (Html.BeginForm()) {
<p>Your name: @Html.TextBoxFor(x => x.Name) </p>
<p>Your email: @Html.TextBoxFor(x => x.Email)</p>
<p>Your phone: @Html.TextBoxFor(x => x.Phone)</p>
<p>
47
this:
...
...
The HTML TextBoxFor helper method generates the HTML for an input
element, sets the type parameter to text, and sets the id and name attributes
to Phone (the name of the selected domain class property) like this:
This handy feature works because the RsvpForm view is strongly typed,
and I have told MVC that GuestResponse is the type that I want to render
with this view. This provides the HTML helper methods with the
information they need to understand which data type I want to read
properties from via the @model expression.
...
@Html.TextBox("Email")
...
165
Designing Mvc Application
166
Advanced Web Technologies Handling Form:
We have not yet told MVC what we want to do when the form is posted to
the server. As things stand, clicking the Submit RSVP button just clears
any values we have entered into the form. That is because the form posts
back to the RsvpForm action method in the Home controller, which just
tells MVC to render the view again.
To receive and process submitted form data, use a clever feature and add
a second RsvpForm action method in order to create the following:
1. A method that responds to HTTP GET requests: A GET request is
what a browser issues normally each time someone clicks a link. This
version of the action will be responsible for displaying the initial
blank form when someone first visits/Home/RsvpForm.
2. A method that responds to HTTP POST requests: By default, forms
rendered using Html.BeginForm()are submitted by the browser as a
POST request. This version of the action will be responsible for
receiving submitted data and deciding what to do with it.
Handing GET and POST requests in separate C# methods helps to
keep my controller code tidy, since the two methods have different
responsibilities. Both action methods are invoked by the same URL,
but MVC makes sure that the appropriate method is called, based on
whether I am dealing with a GET or POST request. Listing 3.7 shows
the changes to applied to the HomeController class.
Listing 3.7.
Adding an Action Method to Support POST Requests in the
HomeController.cs File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PartyInvites.Models;
namespace PartyInvites.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
int hour = DateTime.Now.Hour;
ViewBag.Greeting = hour < 12 ? "Good Morning" : "Good
Afternoon";
return View();
}[
HttpGet]
167
public ViewResult RsvpForm() { Designing Mvc Application
return View();
}[
HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
// TODO: Email response to the party organizer
return View("Thanks", guestResponse);
}
}
}
169
using System.ComponentModel.DataAnnotations; Designing Mvc Application
namespace PartyInvites.Models
{
public class GuestResponse
{
[Required(ErrorMessage = "Please enter your name")]
public string Name { get; set;}
[Required(ErrorMessage = "Please enter your email address")]
[RegularExpression(".+\\@.+\\..+",
ErrorMessage = "Please enter a valid email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter your phone number")]
public string Phone { get; set; }
[Required(ErrorMessage = "Please specify whether you'll attend")]
public bool? WillAttend {get; set;}
}
}
There has been a validation problem using the ModelState.IsValid
property in the controller class.
Listing 3.10 shows how I have done this in the POST-enabled RsvpForm
action method in the Home controller class.
Listing 3.10 Checking for Form Validation Errors in the
HomeController.cs File
...
[HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
if (ModelState.IsValid) {
// TODO: Email response to the party organizer
return View("Thanks", guestResponse);
} else {
// there is a validation error
return View();
}
}
170
Advanced Web Technologies If there are no validation errors, then MVC to render the Thanks view, just
as we did previously. If there are validation errors, re-render the
RsvpForm view by calling the View method without any parameters.
Just displaying the form when there is an error is not helpful—also need to
provide the user with some indication of what the problem is and why we
could not accept their form submission. I do this by using the
Html.ValidationSummary helper method in the RsvpForm view, as shown
in Listing 3.11
Listing 3.11
Using the Html.ValidationSummary Helper Method in the
RsvpForm.cshtml File
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>RsvpForm</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p>Your name: @Html.TextBoxFor(x => x.Name) </p>
<p>Your email: @Html.TextBoxFor(x => x.Email)</p>
<p>Your phone: @Html.TextBoxFor(x => x.Phone)</p>
<p>
Will you attend?
@Html.DropDownListFor(x => x.WillAttend, new[]
{
171
</p> Designing Mvc Application
172
Advanced Web Technologies <input class="input-validation-error" data-val="true" data-val-
required="Please enter your name" id="Name" name="Name" type="text"
value="" />
The highlighted the difference in bold: the helper method added a class
called input-validation-error to the input element. It can take advantage of
this feature by creating a style sheet that contains CSS styles for this class
and the others that different HTML helper methods apply.
The convention in MVC projects is that static content, such as CSS style
sheets, is placed into a folder called Content. Create this folder by right-
clicking on the PartyInvites item in the Solution Explorer, selecting Add
New Folder from the menu and setting the name to Content.
To create the CSS file, right click on the newly created Content folder,
select Add New Item from the menu and choose Style Sheet from the set
of item templates. Set the name of the new file to Styles.css
173
JavaScript and CSS style sheets to be consolidated and delivered to the Designing Mvc Application
browsers over a single HTTP request.
Adding the Link Element in the RsvpForm.cshtml File.
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
} <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" type="text/css" href="∼/Content/Styles.css"/>
<title>RsvpForm</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p>Your name: @Html.TextBoxFor(x => x.Name) </p>
<p>Your email: @Html.TextBoxFor(x => x.Email)</p>
<p>Your phone: @Html.TextBoxFor(x => x.Phone)</p>
<p>
Will you attend?
@Html.DropDownListFor(x => x.WillAttend, new[]
{
new SelectListItem() {Text = "Yes, I'll be there",
Value = bool.TrueString},
new SelectListItem() {Text = "No, I can't come",
Value = bool.FalseString}
}, "Choose an option")
</p>
<input type="submit" value="Submit RSVP" />
}
</body>
</html>
174
Advanced Web Technologies
175
Designing Mvc Application
176
Advanced Web Technologies <div class="form-group">
<label>Your name:</label>
@Html.TextBoxFor(x => x.Name, new { @class = "formcontrol"})
</div>
<div class="form-group">
<label>Your email:</label>
@Html.TextBoxFor(x => x.Email, new { @class = "formcontrol"})
</div>
<div class="form-group">
<label>Your phone:</label>
@Html.TextBoxFor(x => x.Phone, new { @class = "formcontrol"})
</div>
<div class="form-group">
<label>Will you attend?</label>
@Html.DropDownListFor(x => x.WillAttend, new[] {
new SelectListItem() {Text = "Yes, I'll be
there",
Value = bool.TrueString},
new SelectListItem() {Text = "No, I can't
come",
Value = bool.FalseString}
}, "Choose an option", new { @class = "formcontrol" })
</div>
<div class="text-center">
<input class="btn btn-success" type="submit"
value="Submit RSVP" />
</div>
}
</div>
</div>
</body>
</html>
The Bootstrap classes in this example create a panel with a header, just to
give structure to the layout. To style the form, used the form-group class,
which is used to style the element that contains the label and the
associated input or select element.
177
These elements are created using HTML helper methods, which means Designing Mvc Application
that there are not statically defined elements available to which I can apply
the required form-control class. Fortunately, the helper methods take an
optional object argument that lets me specify attributes on the elements
that they create, as follows:
@Html.TextBoxFor(x => x.Name, new { @class = "form-control"})
178
Advanced Web Technologies body { background-color: #F1F1F1; }
</style>
</head>
<body>
<div class="text-center">
<h1>Thank you, @Model.Name!</h1>
<div class="lead">
@if (Model.WillAttend == true)
{
@:It's great that you're coming. The drinks are already in
the fridge!
}
else
{
@:Sorry to hear that you can't make it, but thanks for
letting us know.
}
</div>
</div>
</body>
</html>
179
namespace LanguageFeatures.Models { Designing Mvc Application
180
Advanced Web Technologies }
}
We can see that the property value is read and set just like a regular field.
Using properties is preferable to using fields because we can change the
statements in the get and set blocks without needing to change the classes
that depend on the property.
Product name: Kayak
Properties added to the Product class in the Product.cs file.
Verbose Property Definitions in the Product.cs File
namespace LanguageFeatures.Models
{
public class Product
{
private int productID;
private string name;
private string description;
private decimal price;
private string category;
public int ProductID
{
get { return productID; }
set { productID = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}/
/...and so on...
}
}
181
Designing Mvc Application
10.4 USING AUTOMATICALLY IMPLEMENTED PROPERTIES
182
Advanced Web Technologies public string Category {set; get;}
}
}
Note that I must implement both the getter and setter to return to a regular
property. C# does not support mixing automatic- and regular-style getters
and setters in a single property.
(object)String.Format("Category: {0}",
myProduct.Category));
}
}
}
Using the Object Initializer Feature in the HomeController.cs File
...
public ViewResult CreateProduct()
{
// create and populate a new Product object
Product myProduct = new Product
{
ProductID = 100, Name = "Kayak",
Description = "A boat for one person",
Price = 275M, Category = "Watersports"
};
return View("Result",(object)String.Format("Category: {0}",
myProduct.Category));
}
Initializing Collections and Arrays in the HomeController.cs File
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using LanguageFeatures.Models;
namespace LanguageFeatures.Controllers {
public class HomeController : Controller {
public string Index()
{
return "Navigate to a URL to show an example";
}/
/ ...other action methods omitted for brevity...
public ViewResult CreateCollection()
{
string[]stringArray = { "apple", "orange", "plum" };
List<int> intList = new List<int> { 10, 20, 30, 40 };
Dictionary<string, int> myDict = new Dictionary<string, int>
184
Advanced Web Technologies {
{ "apple", 10}, {"orange", 20}, {"plum", 30}
};
return View("Result", (object)stringArray[1]);
}
}
}
}r
eturn total;
}
}
}
Applying an Extension Method in the HomeController.cs File
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using LanguageFeatures.Models;
namespace LanguageFeatures.Controllers
{
public class HomeController : Controller
{
public string Index()
{
return "Navigate to a URL to show an example";
}/
/ ...other action methods omitted for brevity...
public ViewResult UseExtension()
{
// create and populate ShoppingCart
ShoppingCart cart = new ShoppingCart
{
Products = new List<Product>
{
new Product {Name = "Kayak", Price = 275M},
new Product {Name = "Lifejacket", Price = 48.95M},
new Product {Name = "Soccer ball", Price = 19.50M},
new Product {Name = "Corner flag", Price = 34.95M}
}
};
// get the total value of the products in the cart
decimal cartTotal = cart.TotalPrices();
return View("Result",
186
Advanced Web Technologies (object)String.Format("Total: {0:c}", cartTotal));
}
}
}
187
public static IEnumerable<Product> Filter Designing Mvc Application
188
Advanced Web Technologies return prod.Category == "Soccer";
};
decimal total = 0;
foreach (Product prod in products.Filter(categoryFilter))
{
total += prod.Price;
}
return View("Result", (object)String.Format("Total: {0}", total));
}
Using a Lambda Expression to Replace a Delegate Definition in the
HomeController.cs File
public ViewResult UseFilterExtensionMethod()
{
// create and populate ShoppingCart
IEnumerable<Product> products = new ShoppingCart {
Products = new List<Product> {
new Product {Name = "Kayak", Category = "Watersports", Price =
275M},
new Product {Name = "Kayak", Category = "Watersports", Price =
48.95M},
new Product {Name = "Soccer ball", Category = "Soccer", Price
= 19.50M},
new Product {Name = "Corner flag", Category = "Soccer", Price
= 34.95M}
}
};
Func<Product, bool> categoryFilter = delegate(Product prod)
{
return prod.Category == "Soccer";
};
189
decimal total = 0; Designing Mvc Application
MVC Pattern:
The history of MVC Pattern:
The time period version-view-controller has been in use since the past due
1970s and arose from the Smalltalk challenge at Xerox PARC, wherein it
became conceived as a way to arrange a few early GUI applications. Some
of the first-class detail of the authentic MVC sample changed into tied to
Smalltalk-unique standards, including monitors and tools, however the
broader standards are nonetheless relevant to programs—and they may be
specifically nicely acceptable to Web applications.
Interactions with an MVC software observe a herbal cycle of consumer
movements and examine updates, where the view is assumed to be
stateless. This fits well with the HTTP requests and responses that
underpin a Web utility.
Further, MVC forces a separation of worries—the domain version and
controller logic are decoupled from the user interface. In a Web
application, which means that the HTML is kept apart from the relaxation
of the software, which makes maintenance and testing simpler and easier.
It become Ruby on Rails that led to renewed mainstream interest in MVC
and it remains the implementation template for the MVC pattern. Many
different MVC frameworks have seeing that emerged and confirmed the
advantages of MVC—including, of path, ASP.NET MVC.
190
Advanced Web Technologies The ASP.NET Implementation of MVC:
In MVC, controllers are C# lessons, normally derived from the
System.Web.Mvc.Controller elegance. Each public technique in a
category derived from Controller is an movement approach, which is
related to a configurable URL through the ASP.NET routing device. When
a request is despatched to the URL related to an movement approach, the
statements in the controller magnificence are completed on the way to
carry out a few operation on the domain model and then choose a view to
display to the consumer. Figure shows the interactions between the
controller, model, and view.
The ASP.NET MVC Framework uses a view engine, which is the
component responsible for processing a view in order to generate a
response for the browser. Earlier versions of MVC used the standard
ASP.NET view engine, which processed ASPX pages using a streamlined
version of the Web Forms markup syntax. MVC 3 introduced the Razor
view engine, which was refined in MVC 4 (and unchanged in MVC5) and
that uses a different syntax entirely.
Helper:
Creating custom helper method:
The simplest kind of helper method is an inline helper, which is defined
within a view. I can create an inline helper to simplify the example view
using the @helper tag, as shown in Listing 21-3.
Listing .
Creating an Inline Helper Method in the Index.cshtml File
@model string
@{
Layout = null;
}
@helper ListArrayItems(string[] items)
{
foreach(string str in items)
{
<b>@str </b>
}
}
<!DOCTYPE html>
<html>
191
<head> Designing Mvc Application
192
Advanced Web Technologies Listing:
The Contents of the CustomHelpers.cs File
using System.Web.Mvc;
namespace HelperMethods.Infrastructure
{
public static class CustomHelpers
{
public static MvcHtmlString ListArrayItems(this HtmlHelper html,
string[] list)
{
TagBuilder tag = new TagBuilder("ul");
foreach(string str in list)
{
TagBuilder itemTag = new TagBuilder("li");
itemTag.SetInnerText(str);
tag.InnerHtml += itemTag.ToString();
}
return new MvcHtmlString(tag.ToString());
}
}
}
193
public string Category { set; get; } Designing Mvc Application
}
}
10.11 SUMMARY
In this chapter, we created a new MVC project and used it to assemble a
simple MVC facts-entry application, giving you a first glimpse of the
MVC Framework structure and approach. We ignored some key
capabilities (consisting of Razor syntax, routing, and automated testing),
however we come back to those topics in depth in later chapters. In the
subsequent bankruptcy,describe the MVC structure, design styles, and
strategies that we use all through the relaxation of this e-book and which
form the foundation for powerful improvement with the MVC Framework.
*****
194
11
VIEW
Unit structure
11.0 Objective
11.1 Reduce duplication in views
11.2 Specify a default layout
11.3 Pass data values to the view from the controller
11.4 Generate different content based on data values
11.5 Add a namespace to a view
11.6 Summary
11.7 Unit end Exercises
11.8 List of References
11.0 OBJECTVIES
1. In this chapter we learn using Partial views how to reduce the
duplication in views?
2. How to specify a default layout in views?
3. How to pass data values to the view from the controller?
4. How to generate different content based on the data values?
5. How add a namespace to a view?
195
Creating Partial View: View
Click the Add button and Visual Studio will create partial view, which is
initially empty. After adding the content as following in The Content of
the MyPartial.cshtml File
This is the message from the partial view. @Html.ActionLink ("This is a
link to the Index action", "Index")
Note: use Add MVC 5 View page (razor) and set contents you require
directly.
Consuming a Partial View in the List.cshtml File @{ ViewBag.Title =
"List"; 548 Layout = null; }
This is THE/Views/Common/List.cshtml
View@Html.Partial(“MyPartial”)
We specify the name of the partial view file without the file extension.
The view engine will look for the partial view that we have specified in
the usual locations, which means the /Views/Home and /Views/Shared
folders for this example, since we called the Html.Partial method in a view
that is being rendered for the Home controller. (I set the Layout variable to
null so that we do not have to specify the sections we defined in
the_Layout.cshtml file used earlier in the chapter
196
Advanced Web Technologies
We can create strongly typed partial views, and then pass view model
objects to be used when the partial view is rendered. To demonstrate this
feature, created a new typed partial view called
MyStrongTypedPartial.cshtml in the/View/Shared folder. This time, rather
than use the scaffold option, after selected Add MVC 5 View page, set the
name MyStrongTypedPartial and clicked the OK button to create the
view. As explained previous there is nothing about the file itself that
denotes a partial view, just the content and the way it is used.
The Contents of the MyStronglyTypedPartial.cshtml File.
@model IEnumerable<string>
<div>
This is the message from the partial view
<ul> @foreach(string str in model)
{
<li>@str</li>
}
</div>
We use a Razor @foreach loop to display the contents of the view model
object as items in an HTML list. To demonstrate the use of this partial
view, we updated the/Views/Common/List.cshtml file as shown in
Consuming a Strongly Typed Partial View in the List.cshtml File
@{
ViewBag.Title = "List";
Layout = null;
}<
h3>This is the /Views/Common/List.cshtml View</h3>
@HTML Partial(“MyStronglyTypedPartial”,new
[]{“Apple,”Orange”,”Pear”})
The difference from the previous example is that I pass an additional
argument to the Partial helper method which defines the view model
object. You can see the strongly typed partial view in use by starting the
application and navigating to the
197
/Home/List URL, as shown View
198
Advanced Web Technologies [ChildActionOnly]
public ActionResult Time()
{
return PartialView(DateTime.Now);
}
}
}
The action method is called Time and it renders a partial view by calling
the PartialView method. The ChildActionOnly attribute ensures that an
action method can be called only as a child method from
within a view. An action method doesn‟t need to have this attribute to be
used as a child action, but I tend to use it to prevent the
action methods from being invoked as a result of a user request.
Having defined an action method, I need to create the partial view that will
be rendered when the action is invoked. Child actions are typically
associated with partial views, although this is not compulsory.
the/Views/Home/Time.cshtml view that I created for this demonstration.
This is a strongly typed partial view whose view model is a DateTime
object.
The Contents of the Time.cshtml File
@model DateTime
<p>The time is: @Model.ToShortTimeString()</p>
Child actions are called using the Html.Action helper with this helper the
action method is executed, the ViewResult is processed, and the output is
injected into the response to the client.
As shown following changes has been shows the changes made to the
/Views/Common/List.cshtml file to render the child action.
199
You can see the effect of the child action by starting the application and View
navigating to the /Home/List URL again, as shown in figure.
HEADER
FOOTER
200
Advanced Web Technologies
11.2 SPECIFY A DEFAULT LAYOUT
The layout view has extension like other view such as .cshtml or
.vbhtml,Layout views are shared with multiple views, so it stored in the
shared folder compulsory. By default a layout view _Layout.cshtml is
created when we are creating MVC application ,
Adding Markup to the ProductSummary.cshtml File
@model SportsStore.Domain.Entities.Product
<div class="well">
<h3>
<strong>@Model.Name</strong>
<span class="pull-right label
labelprimary">@Model.Price.ToString("c")</span>
</h3>
<span class="lead"> @Model.Description</span>
</div>
Now need to update Views/Products/List.cshtml so that it uses the partial
view
201
View
View Bag:
View Bag uses dynamic feature that was added in C# 4.0,
ViewBag=ViewData + Dynamic wrapper around the ViewData
Dictionary.
202
Advanced Web Technologies 4.
5. Just type code for implementing property automatically and press tab
button which is available on the keyboard twice
203
8. Select an Empty Controller from the list of Scaffold. View
204
Advanced Web Technologies 15.
Now assign the variable into ViewBag, all properties will be in place
16. Insert the code:
@using PassDetainMVC.Models
@{
ViewBag.Title= “Index”;
}
<h3> Passing data from controller to View </h3>
@{
Var data=ViewBag.Message;
}
<h3> Id: @data.Id</h3>
<h3> ResultName:@data.ResultName</h3>
<h3> ResultDetail:@data.ResultDetail</h3>
Now build and execute/run the code you will get output.
205
Id= „97‟; View
ResultName= “M.Sc.IT”;
ResultDetail= “ The basic Sheet”;
}
ViewData[“Message”]=res;
return View();
}
}
3. Access model class when you are using ViewData
4. @using PassDatainMVC.Models
5. @{
6. ViewBag.Title = "Index";
7. }
8. <h3>Passing Data From Controller To View using
ViewData</h3>
9. @{
10. var data = (Record)ViewData["Message"];
11. }
12. <h3>Id: @data.Id</h3>
13. <h3>ResultName: @data.ResultName</h3>
14. <h3>ResultDetail: @data.ResultDetail</h3>
Then build and run the code you will get output.
11.6 SUMMARY
In this chapter we have leaned about the how to Reduce duplication in
views, Specify a default layout, Pass data values to the
view from the controller, generate different content based on data values,
add namespace to view in MVC application.
207
11.8 LIST OF REFERENCES View
*****
208