PDF-of-Advance-Web-Technologies-LAb-munotes

Page 1

1
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 app lication.
 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 developme nt. 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. munotes.in

Page 2


2 Windows Forms Application, Classes And Objects, Ui Object oriented: It is truly object oriented and supports Encapsulation,
Inheritance
and polymorphism concepts of OOPs.
The entire C# class model is built o n top of the Virtual Object System of
the
.NET Framework In C#, everything is an object. There are no more global
functions, variables and constants.
Type safe: Type -safety promotes robust programs. C# incorporates a
number of type -safe measures:
 All dyna mically allocated objects and arrays are initialized to zero.
 Use of any uninitialized variables produces an error message by the
compiler.
 Access to arrays is range -checked and warned if it goes out -of-
bounds.
 C# does not permit unsafe casts.
 C# enforces overflow checking in arithmetic operations.
 Reference parameters that are passed are type -safe.
 C# supports automatic garbage collection.
It is versonable : Making new versions of software modules work with the
existing applications is known as versioning. C# provides support for
versioning with the help of new and override keywords.
It is compatible: C# enforces the NET common language specifications
and therefore allows inter -operation with other .NET languages.
It is Interoperable and Flexible: Although C # does not support pointers,
we may declare certain classes and methods as „unsafe‟ and then use
pointers to manipulate them. However, these codes will not be type -safe.
Name space: It is having namespaces; a namespace to define a declarative
region
Applic ations 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 munotes.in

Page 3


3 Advanced Web Technologies  Developing ASP.NET projects:
 Creating Web controls
 Providing Web services
 Developing NET component library
1.1.3 C# and .NET:
The .NET framework is responsible for executing the C# program in the
system. Framework is the combination of common language runtime and a
set of class libraries. The implementation of Common Language
Infrastructur e (CLI) is done through Common Language Runtime (CLR).
Microsoft .NET framework consists of the following main components:
 Common Language Runtime
 Base class library
 User Program interfaces
It also supports Common Type System (CTS) which sstandardizes the data
types of all programming languages using .NET under the umbrella of
.NET to a common data type for easy and smooth communication among
these .NET languages
1.2 AN OVERVIEW ABOUT C# The elements of Visual Studio .NET applications are mentioned below:
1) The Start Page
2) Solution Explorer window
3) Output Window
4) Class View Window
5) Code Editor Window
6) Error List Window
7) Standard ToolBar




munotes.in

Page 4


4 Windows Forms Application, Classes And Objects, Ui 1.2.1 A Simple program :


1.2.2 C# Program Structure :


1. Reference of.NET framework namespaces: Every .NET application
takes the reference of the necessary .NET framework namespaces that
it is planning to use with the using (Keyword) , Ex., using System;
2. namespace: (Keyword) Declares the namespace for the cu rrent class
Ex. Structure
3. class: (Keyword) Declares a class: Ex. DemoPrg2
4. Method : Main() is a method of DemoPrg2 class which is the entry
point of the console application.
5. String: It is a data type. Fig 1.2 Simple C# Program munotes.in

Page 5


5 Advanced Web Technologies 6. variable : msgs is a variable that holds the value of the specified (here
it is string) data type.
7. value : “Structure of C# Program” is the value of the message variable
„msgs‟.
8. static method: The Console.WriteLine() is used to display a text on
the console.
9. Ouput screen shows the output of t he program.
10. Every line or statement in C# must end with a semicolon (;).
Compile and Run C# Program :
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. S.No. Data Types Examples datatype = value;
1 Value Types Predefined Types (Simple Types) 1. Integers int a = 99; 2. Real Numbers float b=99.9f; 3. Booleans bool c = true; 4. Characters char d = 'E'; User-defined Types 1. Enumerations enum fruits{ apple, orange, grapes} 2. Structure struct Coordinate { public int x; public int y; } 2 Reference Types Predefined Types 1. Objects public class Car{ public model { get; set; } public int year { get; set; } public string color{ get; set; } } 2. Strings string msg=”Happy”; munotes.in

Page 6


6 Windows Forms Application, Classes And Objects, Ui User-defined Types 1. Classes public class MyClass { } 2. Arrays var num = new int[]{ 1,2,3,4,5}; 3. Delegates public delegate void MyDelegate(string msg); 4. Interfaces interface IFile { void ReadFile(); void WriteFile(string text); } 3 Pointers (type *var-name; ) int x = 4000; 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
C# has some contextual keywords, shown in Table 1.3. They act as
keywords in a special meaning in certain contexts. But they are not
technically reserved. Apart from those contexts, they can be used as names
for other program elements, such as variable n ames. It is a best practice to
avoid using contextual keywords for other purposes. munotes.in

Page 7


7 Advanced Web Technologies Decision Making Statements :
if Statement : If (condition) statement; else statement; if (10 Single statement target s
 else clause is optional if(condition)
{
statement sequence
}
else
{
statement
sequence
} if (10{
Console.WriteLine("You are Correct");
}
else
{
Console.WriteLine("Check the value of
i");
}
if-else-if Ladder : If (condition) statement; else if (condition) statement; else if (condition) statement; ... else statement; if (10The for Loop :
The general form of the for loop for repeating a single statement is for (initialization; condition; iteration) { statement sequence } for(int n = 10; i < 25; i++) { Console.WriteLine("Value of n is:”, n); }
The while Loop
Another of C#‟s loops is the while. The general form of the while loop is munotes.in

Page 8


8 Windows Forms Application, Classes And Objects, Ui while(condition) statement while (n<=10){ Console.WriteLine("Value of n is :", n); n=n+2; } do { statements; } while (condition); do{ sum= sum+n; Console.WriteLine); n=n+2; } while (n <= 20);
1.3 WEB FORMS APPLICATION Design UI based applications using basic Windows forms Controls :



munotes.in

Page 9


9 Advanced Web Technologies PROGRAM TO ADD TWO NUMBERS :
using System;
using System.Collections.Generic;
using System.Co mponentModel;
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()
{
Initializ eComponent();
}

private void button1_Click(object sender, EventArgs e)
{
int a, b, c;
a = Convert.ToInt32(textBox1.Text);
b = Convert.ToInt32(textBox2.Text);
c = a + b;
textBox3.Text = c.ToString();
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
munotes.in

Page 10


10 Windows Forms Application, Classes And Objects, Ui Output:


1.4 CLASSES AND OBJECTS General structure of Class :
To define a class, declare the data that it contains and the code that
operates on it. Simple classes contain only code or only data, most real -
world classes contain both.
Data is contained in data members defined by the class, and code is
contained in function members.
C# defines different kind of data and function mem bers. For example, data
members (also called fields) include instance variables and static variables
and function members.
Function members include methods, constructors, destructors, indexers,
events, operators, and properties.
A class is created by use of the keyword class.
General fo rm of a simple class definition :
class classname
{ munotes.in

Page 11


11 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 :
Buildi ngs 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 App lications using Classes and Object
using System;
namespace MCAClassObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//Creating object
Calculator calObject = new Calculator();
Consol e.Write("Enter number1 : ");
int n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number2 : ");
int n2 = Convert.ToInt32(Console.ReadLine());
//Accessing Calculator class member using Calculator class object
int result1 = calObject.CalculateSum(n1, n2);
int result2 = calObject.CalculateMinus(n1, n2);
int result3 = calObject.CalculateMul(n1, n2); munotes.in

Page 12


12 Windows Forms Application, Classes And Objects, Ui Console.WriteLine("The Sum of Two numbers is : " + result1);
Cons ole.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 Reg istration
forms and advanced controls :

munotes.in

Page 13


13 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 Registr ation
{
public partial class Form1 : Form
{
public Form1()
{ munotes.in

Page 14


14 Windows Forms Application, Classes And Objects, Ui InitializeComponent();
}
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 Sq lCommand("select * from LoginTable where username='" +
txtusername.Text + "'", cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Userna me Already exist please try another ", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
cmd = new SqlCommand("insert into LoginTable
values(@username,@password)", cn);
cmd.Parameters.AddWithValue("username", txtusername.Text);
cmd.Parameters.AddWithValue("password", txtpassword.Text); munotes.in

Page 15


15 Advanced Web Technologies cmd.ExecuteNonQuery();
MessageBox.Show("Your Account is created . Please login now.",
"Done", Mess ageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("Please enter both password same ", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please enter value in all field.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

1.6 INHERITANCE 1.6.1 Inheritance Concept s 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. munotes.in

Page 16


16 Windows Forms Application, Classes And Objects, Ui The following class called TwoDShape stores the width and height of a
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 progra m uses TwoDShape to derive a class called
Triangle. Pay close attention to the way that Triangle is declared.
Design Applications using Inheritance and Abstract Classes :
// A simple class hierarchy.
using System;
// A class for two -dimensional objects.
class TwoDShape
{
public double Width;
public double Height;
public void ShowDim()
{
Console.WriteLine("Width and height are " + Width + " and " + Height);
}
}
// Triangle is derived from TwoDShape.
class Triangle : TwoDShape
{
public string Style; // styl e of triangle
// Return area of triangle.
public double Area()
{
return Width * Height / 2;
}
// Display a triangle's style.
public void ShowStyle()
{
Console.WriteLine("Triangle is " + Style); munotes.in

Page 17


17 Advanced Web Technologies }
}
class Shapes
{
static void Main()
{
Triangle t1 = new Triangle();
Triangle t2 = new Triangle();
t1.Width = 4.0;
t1.Height = 4.0;
t1.Style = "isosceles";
t2.Width = 8.0;
t2.Height = 12.0;
t2.Style = "right";
Console.WriteLine("Info for t1: ");
t1.ShowStyle();
t1.ShowDim();
Console.WriteLine("Area is " + t1.Are a());
Console.WriteLine();
Console.WriteLine("Info for t2: ");
t2.ShowStyle();
t2.ShowDim();
Console.WriteLine("Area is " + t2.Area());
}
}
The output from this program is shown here:
Info for t1:
Triangle is isosceles
Width and height are 4 and 4 munotes.in

Page 18


18 Windows Forms Application, Classes And Objects, Ui Area is 8
Info for t2:
Triangle is right
Width and height are 8 and 12
Area is 48
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 abstra ct 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 interf ace. 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, a ny 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 impleme ntation. 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 object s 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 co ntracts 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);
}
munotes.in

Page 19


19 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)
}
// Cat "implements" the IAnimal interface
class Cat : IAnimal
{
public void animalSound()
{
// The body of animalSound() is pr ovided here
Console.WriteLine("The cat says: Miaw Miaw");
}
}
class Program
{
static void Main(string[] args)
{
Cat myCat = new Cat(); // Create a Cat object
myCat.animalSound();
}
}


munotes.in

Page 20


20 Windows Forms Application, Classes And Objects, Ui 1.8 ABSTRACT CLASSES In the hierarchical inh eritance applications, an application can have a
single base class and number of different derived classes. The base class
acts as base for all the other but only the required information is visible to
the derived class. The information to be hidden from t he users of the
derived classes can be implemented using Abstract classes. These classes
contain abstract methods that are inherited by other classes that provide
more functionality. The f eatures of Abstract Classes are :
 The keyword abstract is used to cre ate abstract class .
 Some of the methods of the abstract class can also contain the
keyword abstract.
 No object can be created of the abstract class i.e.it cannot be
instantiated.
 The abstract methods in the abstract class are implemented actually
only in t he derived classes.
Design Applications using Inheritance and Abstract Classes :
using System;
namespace AbstractionDemo
{
abstract class Shape
{
public abstract double area();
}
class Circle: Shape
{
private double radius;
public Circle( double r)
{
radius = r;
}
public override double area ()
{
return (3.14*radius*radius);
}
} munotes.in

Page 21


21 Advanced Web Technologies class Square: Shape
{
private double side;
public Square( double s)
{
side = s;
}
public override double area ()
{
return (side*side);
}
}
class Triangle: Shape
{
private double tbase;
private double theight;
public Triangle( double b, double h)
{
tbase = b;
theight = h;
}
public override double area ()
{
return (0.5*tbase*theight);
}
}
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()); munotes.in

Page 22


22 Windows Forms Application, Classes And Objects, Ui Triangle t = new Triangle(2.0, 5.0);
Console.WriteLine("Area of Triangle = {0}", t.area());
}
}
}
The output of the above p rogram 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 retu rns 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 f unction 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 me mbers
The individual instances of class are known as objects. A class has both
properties and behaviors. munotes.in

Page 23


23 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 th e 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 index ers 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.
1.10 UNIT END EXERCISES 1. State the features and applications of C#.
2. Write a program in C sharp to find odd and even numbers
3. Design a web form for arithmetic operations
4. Write an application to design employee details web form.
1.11 LIST OF REFERENCES 1. Spaanjaars, Imar. Beginning ASP. NET 4.5. 1: in C# and VB. John
Wiley & Sons, 2014 . ISBN: 1861009038
2. Schildt, Herbert. C# 4.0: the complete reference. Tata McGraw -Hill
Education, 2010
3. Balagurusamy E, Programming in C#, Tata McGraw -Hill Education
4. https://www.wideskills.com/csharp/overview -csharp
5. https://www.onlinegdb.com/onli ne_csharp_compiler






*****
munotes.in

Page 24

24
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 servic es. .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
environme nts.
 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 .NET Framework consists of the common language runtime (CLR) and
the .NET Framework class library. The common language runtime is the
foundation of .NET Framework. Think of the runtime as an agent that
manages code at execution time, providing core services such as memory
management, thread management, and remoting, while also enforcing
strict type safety and other forms of code accuracy that promote security
and robustness. In fact, the concept of code management is a fundamental
principle of the runtime. Code that targets the runtime is known as
managed code, while code that doesn't target the runtime is known as
unmanaged code. The class library is a comprehensive, object -oriented munotes.in

Page 25


25 Advanced Web Technologies collection of reusable types that you use to develop apps rang ing from
traditional command -line or graphical user interface (GUI) apps to apps
based on the latest innovations provided by ASP.NET, such as Web Forms
and XML web services.
.NET Framework can be hosted by unmanaged components that load the
common language runtime into their processes and initiate the execution
of managed code, thereby creating a software environment that exploits
both managed and unmanaged features. .NET Framework not only
provides several runtime hosts but also supports the development of third -
party runtime hosts.
Creating a Web a pplication project and a Page :
In this part of the walkthrough, you will create a Web application project
and add a new page to it. You will also add HTML text and run the page
in your browser.
To create a Web ap plication project :
1. Open Microsoft Visual Studio.
2. On the File menu, select New Project .

The New Project dialog box appears.
3. Select the Templates -> Visual C# -> Web templates group on the
left.
4. Choose the ASP.NET Web Application template in th e center
column.
5. Name your project BasicWebApp and click the OK button.
munotes.in

Page 26


26 Introduction to Asp.Net 6. Next, select the Web Forms template and click the OK button to
create the project.

Visual Studio creates a new project that includes prebuilt functionality
based on the Web F orms template. It not only provides you with a
Home.aspx page, an About.aspx page, a Contact.aspx page, but also
includes membership functionality that registers users and saves their
credentials so that they can log in to your website. When a new page is
created, by default Visual Studio displays the page in Source view, where
you can see the page's HTML elements. The following illustration shows
what you would see in Source view if you created a new Web page named
BasicWebApp.aspx.

A Tour of the Visual Studio Web Development Environment :
Before you proceed by modifying the page, it is useful to familiarize
yourself with the Visual Studio development environment. The following
illustration shows you the windows and tools that are available in Visual
Studi o and Visual Studio Express for Web. munotes.in

Page 27


27 Advanced Web Technologies The Visual Studio environment :

Familiarize yourself with the Web designer :
Examine the above illustration and match the text to the following list,
which describes the most commonly used windows and tools. (Not all
windows and tools that you see are listed here, only those marked in the
preceding illustration.)
 Toolbars. Provide commands for formatting text, finding text, and so
on. Some toolbars are available only when you are working in Design
view.
 Solution Explorer window. Displays the files and folders in your
Web application.
 Document window. Displays the documents you are working on in
tabbed windows. You can switch between documents by clicking
tabs.
 Properties window. Allows you to change settings for the page,
HTML elements, controls, and other objects.
 View tabs. Present you with different views of the same document.
Design view is a near -WYSIWYG editing surface. Source view is the
HTML editor for the page. Split view displays both the Design view
and the Sour ce view for the document. You will work with the
Design and Source views later in this walkthrough. If you prefer to
open Web pages in Design view, on the Tools menu, click Options ,
select the HTML Designer node, and change the Start Pages In
option.
 ToolB ox. Provides controls and HTML elements that you can drag
onto your page. Toolbox elements are grouped by common function.
 Server Explorer . Displays database connections. If Server Explorer
is not visible, on the View menu, click Server Explorer. munotes.in

Page 28


28 Introduction to Asp.Net 2.2 SUMMA RY 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.
To add a page to the Web application :
1. Close the Default.aspx page. To do this, click the tab that display s the
file name and then click the close option.
2. In Solution Explorer , right -click the Web application name (in this
tutorial the application name is BasicWebSite ), and then click Add ->
New Item .
The Add New Item dialog box is displayed.
3. Select the Visual C# -> Web templates group on the left. Then, select
Web Form from the middle list and name it FirstWebPage.aspx.

4. Click Add to add the web page to your project.
Visual Studio creates the new page and opens it.
Adding HTML to the Page :
In this pa rt of the walkthrough, you will add some static text to the page.
To add text to the page :
1. At the bottom of the document window, click the Design tab to switch
to Design view.
Design view displays the current page in a WYSIWYG -like way. At
this point, y ou do not have any text or controls on the page, so the munotes.in

Page 29


29 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.

4. Switch to Source view.
You can see the HTML in Source view that you created when you
typed in Design view.

Running the Page :
Before yo u proceed by adding controls to the page, you can first run it.
munotes.in

Page 30


30 Introduction to Asp.Net To run the page :
1. In Solution Explorer , right -click FirstWebPage.aspx and select Set
as Start Page .
2. Press CTRL+F5 to run the page.
The page is displayed in the browser. Although the page you created
has a file -name extension of .aspx, it currently runs like any HTML
page.
To display a page in the browser you can also right -click the page in
Solution Explorer and select View in Browser .
3. Close the browser to stop the Web application.
Adding and Programming Controls :
You will now add server controls to the page. Server controls, such as
buttons, labels, text boxes, and other familiar controls, provide typical
form -processing capabilities for your Web Forms pages. However, you
can program t he controls with code that runs on the server, rather than the
client.
You will add a Button control, a TextBox control, and a Label control to
the page and write code to handle the Click event for the Button control.
To add controls to the page :
1. Click the Design tab to switch to Design view.
2. Put the insertion point at the end of the Welcome to Visual Web
Developer text and press ENTER five or more times to make some
room in the div element box.
3. In the Toolbox , expand the Standard group if it is no t already
expanded.
Note that you may need to expand the Toolbox window on the left to
view it.
4. Drag a TextBox control onto the page and drop it in the middle of the
div element box that has Welcome to Visual Web Developer in the
first line.
5. Drag a B utton control onto the page and drop it to the right of the
TextBox control.
6. Drag a Label control onto the page and drop it on a separate line
below the Button control.
7. Put the insertion point above the TextBox control, and then type
Enter your name: munotes.in

Page 31


31 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.

Setting Control Properties :
Visual Studio offers y ou various ways to set the properties of controls on
the page. In this part of the walkthrough, you will set properties in both
Design view and Source view.
To set control properties :
1. First, display the Properties windows by selecting from the View
menu -> Other Windows -> Properties Window . You could
alternatively select F4 to display the Properties window.
2. Select the Button control, and then in the Properties window, set the
value of Text to Display Name . The text you entered appears on the
button i n the designer, as shown in the following illustration.

3. Switch to Source view.
Source view displays the HTML for the page, including the elements
that Visual Studio has created for the server controls. Controls are
declared using HTML -like syntax, exc ept that the tags use the prefix
asp: and include the attribute runat="server" .
Control properties are declared as attributes. For example, when you
set the Text property for the Button control, in step 1, you were
actually setting the Text attribute in th e control's markup.
Note: All the controls are inside a form element, which also has the
attribute runat="server" . The runat="server" attribute and the asp:
prefix for control tags mark the controls so that they are processed by munotes.in

Page 32


32 Introduction to Asp.Net ASP.NET on the server whe n the page runs. Code outside of

runat="server"> and
munotes.in

Page 55


56 Basic Server-Side Control

<%# Container.DataItem %>< br>



A Visual Basic .NET sample pa ge appears as follows:
ASP.NET (VB) Copy
<%@ Page Language ="vb" %>




<%# Container.DataItem %>< br>



The output appears as follows:
 one
 two
 three
4.3 UNIT END EXERCISE  Write a program containing the following controls:
• A ListBox
• A Button
• An Image
• A Label munotes.in

Page 56


57 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.
4.4 LIST OF REFERENCE 1] Practical ASP.NET Web API
2] ASP.NET Core in Action by Andrew Lock
3] Building RESTful Web Services with .NET Core by Gaurav Aroraa , Tadit
Dash






*****

munotes.in

Page 57

58
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 What You Will Learn in This Chapter:
 Learn the basic classes in ADO.NET and its architecture.
 Learn the different ADO.NET Data Providers.
 Learn about the Connection and Command components.
 Learn about the Working with Stored Procedures.
 Learn about the DataAdapter, DataReader and DataSet components. munotes.in

Page 58


59 Advanced Web Technologies  Learn LINQ with ASP.NET.
 Discuss about the query syntax in LINQ.
 Learn the Entity Framework Architecture.
5.1 AN OVERVIEW  ADO.NET is a set of classes that expose data acces s services to the
Microsoft .NET programmer. ADO.NET provides a rich set of
components for creating distributed, data -sharing applications.
 ADO.NET is an integral part of the Microsoft .NET Framework,
providing access to relational, XML, and application da ta.
 All ADO.NET classes are located at the System.Data namespace with
two files named System.Data.dll and System.Xml.dll. When
compiling code that uses the System.Data namespace, reference both
System.Data.dll and System.Xml.dll.
 Basically speaking, ADO.N ET provides a set of classes to support
you to develop database applications and enable you to connect to a
data source to retrieve, manipulate and update data with your
database.
5.2 INTRODUCTION OF THE ADO.NET ADO.NET is a collection of managed librarie s used by .NET applications
for data source communication using a driver or provider:
Enterprise applications handle a large amount of data. This data is
primarily stored in relational databases, such as Oracle, SQL Server, and
Access and so on. These data bases use Structured Query Language (SQL)
for retrieval of data.
To access enterprise data from a .NET application, an interface was
needed. This interface acts as a bridge between an RDBMS system and a
.NET application. ADO.NET is such an interface that is created to connect
.NET applications to RDBMS systems.
In the .NET framework, Microsoft introduced a new version of Active X
Data Objects (ADO) called ADO.NET. Any .NET application, either
Windows based or web based, can interact with the database using a rich
set of classes of the ADO.NET library. Data can be accessed from any
database using connected or disconnected architecture.
ADO.NET provides mainly the following two types of architectures:
 ConnectedArchitecture:
The ADO.NET Connected architecture considers mainly three types of
objects :
▪ Connection con munotes.in

Page 59


60 Database Programming In Asp.Net ▪ Command cmd
▪ DataReaderdr
 DisconnectedArchitecture:
The ADO.NET Disconnected architecture considers primarily the
following types of objects:
▪ DataSet ds
▪ DataAdapter da
▪ Connection con
5.3 AR CHITECTURE OF ADO.NET Ado.net is a data access technology that allows interaction between
applications and databases.
Types of Architecture :
 Connected Architecture
 Disconnected Architecture
Ado.net is both connection -oriented as well as disconnection orie nted.
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.
5.3.1 Connected Architecture :
 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.
 Conne cted architecture is forward only and read -only. This means the
connected mode will work only in one particular direction i.e. forward
and that too for read -only purpose. Application issues query then read
back results and process them.
 For connected archi tecture, we mainly use the object of the
DataReader class.
 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.
 In connected architecture, the application is dire ctly linked with the
Database.
munotes.in

Page 60


61 Advanced Web Technologies

Fig 5.1 Connected Architecture in ADO.NET
5.3.2 Disconnected Architecture :
 Disconnected architecture refers to the mode of architecture in
Ado.net where the connectivity between the database and application
is not maintai ned for the full time. Connectivity within this mode is
established only to read the data from the database and finally to
update the data within the database.
 This means during the processing of the application, we need data so
that data is fetched from t he database and kept in temporary tables.
After that whenever data is required, it is fetched from the temporary
tables. And finally, when the operations were completed, the
connection was established to update the data within the database
from the tempora ry tables.
 In this mode, application issues query then retrieves and store results
for processing. For this purpose, we use objects of DataAdapter and
DataSet classes.
 In disconnected architecture, a Dataset is used for retrieving data from
the database. T his way there is no need to establish a connection for
the full time because DataSet acts as temporary storage.
munotes.in

Page 61


62 Database Programming In Asp.Net

Fig 5.2 Disconnected Architecture in ADO.NET
Difference between Connected and Disconnected : Connected Disconnected It is Connection Oriented It is Dis-Connection Oriented Connected get high in speed and performance. Disconnected get low in speed and performance. Connected you need to use a read only forward only data reader Disconnected you cannot Data Reader can’t persist the data Data Set can persist the data It is Read only, we can’t update the data We can update data
5.4 COMPONENTS OF ADO.NET Components are designed for data manipulation and faster data access.
Connection, Command, DataReader, DataAdapter, DataSet, and
DataView are the components of ADO.NET that are used to perform
database operations. ADO.NET has two main components that are used
for accessing and manipulating data. They are as follows:
1. Data provider and
2. DataSet

munotes.in

Page 62


63 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:
1. Connect to the Database
2. Prepare an SQL Command
3. Execute the Command
4. Retrieve the results and display them in the application
The Data Provider is physically composed of a binary library file and this
library is in the DLL file format. Sometimes this DLL file depends on
other DLL files, so in fact a Data Provider can be made up of several DLL
files. Based on the different kinds of databases, Data Provider can have
several versions and each version is matched to each kind of database.
There are following different types of data providers included in ADO.Net Data Provider Descr iption Data Provider for SQL Server (SQL Server.NET) It provides data access for Microsoft SQL Server. The System.Data.SqlClient namespace is used Data Provider for OLEDB (OLEDB.NET) It is used for data sources using OLE DB. The System.Data.OleDb namespace is used Data Provider for ODBC (ODBC.NET) It is used for data sources using ODBC. The System.Data.Odbc namespace is used Data Provider for Oracle (Oracle.NET) It is used Oracle data sources. The System.Data.OracleClient namespace is used
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.
DataProvider Properties and Methods : Objects Description Connection This component is used to set up a connection with a data source. Command A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data in a data source. DataReader Data reader is used to retrieve data from a data source in a read-only and forward-only mode DataAdapter This is integral to the working of ADO.Net since data is transferred munotes.in

Page 63


64 Database Programming In Asp.Net Objects Description to and from a database through a data adapter. It retrieves data from a database into a dataset and updates the database. When changes are made to the dataset, the changes in the database are actually done by the data adapter.
Advantages of using Data Providers in ADO.NET :
1) It provides high performance of client -server access over RDBMS
2) It contains trigger providing powerful means for maintaining business
rules at database level
3) It provides referential integrity that supports primary/foreign key
definition
4) It provides data access through table or server side control
5) It is easy to convert the .NET framework to other database engines
6) It contains full server based transaction to elim inate database
corruption
7) It has database security functionality and encryption support
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 Connection Class Associated Database OdbcConnection ODBC Data Source OleDbConnection OLE DB Database SqlConnection SQL Server Database OracleConnection Oracle Database
The connection string is a property of the Connection class and it
provides all necessary information to connect to your data source.
Regularly this connection string contains a quite few parameters to define
a connection, but only five of them are popularly utilized for most data -
driven applications:
munotes.in

Page 64


65 Advanced Web Technologies  Provi der
 Data Source
 Database
 User ID
 Password
A typical data connection instance with a general connection string can be
expressed by the following codes:
Connection = New xxxConnection(“Provider = MyProvider ;” & _
“Data Source = MyServer ;” & _
“Database = MyDatabase ;” & _
“User ID = MyUserID ;” & _
“Password = MyPassWord ;”)
wherexxx should be replaced by the selected Data Provider in your real
application, such as OleDb, Sql or Oracle . You need to use the real
parameter values implemented in y our applications to replace those
nominal values such as MyServer, MyDatabase, MyUserID and
MyPassWord in your application.
Some typical Connection instances are listed below:
OLE DB Data Provider for Microsoft Access Database :
Connection = New
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C: \database \CSE_DEPT.mdb;" & _
"User ID=MyUserID;" & _
"Password=MyPassWord;")
SQL Server Data Provider for SQL Server Database :
Connection = New SqlConnection("Server=localhost ;" + _
"Data Source=Susan \SQLEXPRESS;" + _
"Database=CSE_DEPT;" + _
"Integrated Security=SSPI")
Oracle Data Provider for Oracle Database :
Connection = New OracleConnection("Data Source=XE;" + _
"User ID=system;" + _
"Password=reback")
Example for SQL Server Database :
using System;
using System.Data;
using System.Data.SqlClient; munotes.in

Page 65


66 Database Programming In Asp.Net public partial class _Defau lt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
string conString = "Data Source=(local);Initial
Catalog=Employee;Integrated Security=True";

protected void Button1_Click(object sender, Ev entArgs e)
{
// Creating the object of SqlConnection class
SqlConnectionconObject = new SqlConnection(conString);

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 connectio n 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 Parameter Name Description Data Source Identify the server.Local Machine/Machine Domain Name/Ip Address Initial Catalog Database Name Integrated Security Set to SSIP to make Connection with user’s munotes.in

Page 66


67 Advanced Web Technologies Connection String Parameter Name Description 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 BeginDbTransaction It starts the database transaction ChangeDatabase It changes the current database for an open connection Close It closes the connection to the database CreateCommand It creates and returns the DbCommand object Dispose() It releases the resources used by the component GetHashCode It serves as a default hash function GetSchema() It returns the schema information for the data source munotes.in

Page 67


68 Database Programming In Asp.Net Open It opens the database connection with the settings specified by the ConnectionString object ToString It returns the string containing the name of the component
Open() and Close() are two important methods of Connection object.
Program:
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string conString = "Data Source=(local);Initial
Catalog=Employee;Integra ted Security=True";
SqlConnectionconObject = new SqlConnection(conString);
conObject.Open();
Console.WriteLine("Connection String ::
"+conObject.ConnectionString);
Console.WriteLine(" DataBase :: "+conObject.Database);
Console.WriteLine("DataSource :: " + conObject.DataSource);
Console.WriteLine("ConnectionTimeout :: " +
conObject.ConnectionTimeout);
Console.WriteLine("Connection Sta te :: " + conObject.State);
Console.WriteLine("ServerVersion :: " +
conObject.ServerVersion);
Console.ReadLine();
}
}
}
Output:
Connection String :: Data Source=(local);Initial
Catalog=Employee;Integrat ed Security=True
DataBase :: Employee
DataSource :: (local)
ConnectionTimeout :: 15 munotes.in

Page 68


69 Advanced Web Technologies Connection State :: Open
ServerVersion :: 10.50.1600
Storing connection string in configuration file
If you did not write connection string in config file, then it may crea te
problem. Suppose that, after deploying the project, you have to change the
connection string, then you have to change the connection string in every
page.
It is a good practice to store the connection string for your application in a
config file rather than in every page.
In this scenario, if you have written the connection string in config file,
then the required change will be done in single place (config file) and the
change will be reflect automatically in every page.





Acceccing the connecting string from config file
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
string conn =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
// Creating the object of SqlConnection clas s
SqlConnection conObject = new SqlConnection(conn);
conObject.Open();
if (conObject.State == ConnectionState.Open)
Response.Write("Database Connection is Open");
}
By default, a connection string is enabled w ith connection pooling.
By default, the maximum number of pools is 100, minimum is 0.
Connection pooling is the ability of re -use your connection to the
Database. This means if you enable Connection pooling in the connection
object, actually you enable the re-use of the connection to more than one
user. munotes.in

Page 69


70 Database Programming In Asp.Net 5.4.2.1 Connection Pooling:

Fig. 5.3 Connection Pooling
Connection pooling enables you to re -use your connection to the
Database. It is an optimization technique that will increase the
performance of datab ase programming. By default connection pooling
feature is enabled with connection string. The maximum number of pools
is 100, and minimum is zero.
Connecting to database is time consuming and resource intensive task.
Whenever user wants to connect database , connection string is parsed and
it checks whether given credentials in connection stings are correct or not.
Therefore it takes lots of time to open and close the connection.
To reduce the cost of opening and closing the same connection repeatedly
and in creasing the performance ADO.NET uses connection pooling.
A Connection String in the Web.Config file with connection pooling
option:




SQL Server connection string pooling attributes :
 Connection Lifetime:
o Length of time in seconds after creation after which a connection is
destroyed. The default is 0, indicating that connection will have the
maximum timeout.



munotes.in

Page 70


71 Advanced Web Technologies  Connection Reset:
o Specifies whether the connection is reset when removed from the
pool. The default is true.
 Enlist:
o Specifies whether the connection is automatically enlisted in the
current transaction context of the creation thread if that transaction
context exists. The default is true.
 Load Balance Timeout:
o Length of time in seconds that a connection can remain idle in a
connection pool before being removed.
 Max Pool Size:
o Maximum number of connections allowed in the pool. The default is
100.
 Min Pool Size:
o Minimum number of connections maintained in the pool. The default
is 0.
 Pooling:
o When true, the connection is drawn from the appropriate pool, or if
necessary, created and added to the appropriate pool. The default is
true.
5.4.3 Command :
The Command object works with the Connection object and used to
execute SQL queries or Stored Procedures against the data sourc e. 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 munotes.in

Page 71


72 Database Programming In Asp.Net cmd = new Sq lCommand("INSERT INTO
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);
Steps for executing SQL query with command object :
 Create a Connection Object and initialize with connection string.
 Create the command object and initialize with SQL query and
connection object.
 Open the connection.
 Execute query with the help of any one method of command object.
 Store the result in DataReader object (In case of select SQL query)
 Close the connection.
Some of the Command properties are as lis ted below: Property Description CommandTimeout Contains the length of the timeout of a query, in seconds CommandText It gets or sets the text command against the data source CommandType CommandType is an important property of Command class. This property is used to determine which type of command being executed. CommandType.StoredProcedure: It informs the Command object that the stored procedure munotes.in

Page 72


73 Advanced Web Technologies will be used in place of simple SQL statements. CommandType.Text: It informs the Command object that the CommandText value contains a SQL query. CommandType.TableDirect: It indicates that the CommandText property contains the name of a table Connection It gets or sets the DbConnection used by the DbCommand Parameters It gets the collection of DbParameter objects Site It gets or sets the ISite of the component Transaction It gets or sets the DbTransaction which the
DbCommand object executes UpdatedRowSource It gets or sets the command results applied to
the DataRow
Some of the methods for the Command objects are as shown below: Methods Description Cancel() It attempts to cancel the execution of the DbCommand CreateDbParameter It creates a new instance of DbParameter object Dispose() It releases all the resources used by the component ExecuteDbDataReader It executes the command text against the connection ExecuteNonQuery It executes SQL statement against the connection object If you are using Insert, Update or Delete SQL statement then use this method. Its return type is Integer (The number of affected records). munotes.in

Page 73


74 Database Programming In Asp.Net ExecuteReader() It executes the CommandText against the Connection object This method works on select SQL query. It returns the DataReader object. Use DataReader read () method to retrieve the rows. ExecuteScalar() Executes the CommandText property and
returns data in a DataReader object.
This method returns single value. Its return
type is Object. When you want single value
(First column of first row), then use
ExecuteScalar () method. Extra columns or
rows are ignored. ExecuteScalar method
gives better performance if SQL statements
have a ggregate function. GetService It returns an object representing a service
object for the instance ExecuteXMLReader ● It returns an instance of XmlReader class.
This method is used to return the result set in
the form of an XML document.
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.Command Text = "select * from tblemps";
cmd.CommandType = CommandType.Text;
try munotes.in

Page 74


75 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();
}
}
}
5.4.3.1 Working With Stored Procedures With Command Object:
First we understand that what is stored procedure and then we will use the
stored procedure in our database program.
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
proced ure.
Creating Stored Procedure :
Open Microsoft SQL Server, select your database, right click and select
create new stored procedure tab.
Here we have created a simple stored procedure named
"GetAllEmployees ". It selects all the record from table tblEmps. munotes.in

Page 75


76 Database Programming In Asp.Net CREATE PROCEDURE [dbo].[GetAllEmployees]
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
Disp lay data using stored procedure :
Just change the previous code as follows and you will get the same result.
SqlConnection con = new SqlConnection("Data Source=(local);Initial
Catalog=Employee;Integrated Security=True");
SqlCommandcmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetAllEmployees";
Insert Record using stored procedure :
First create a simple input screen to insert the data into database as given
below.
Create a Stored Procedure with Input Parameter in the database.
CREATE PROCEDURE InsertEmployees
@EmpID integer,
@EmpNamevarchar(100),
@Gender varchar(50),
@Salary money,
@Address varchar(200),
@DepID integer
AS
BEGIN
-- Insert state ments for procedure here
insert into tblEmps values(@EmpID,@EmpName ,@Gender
,@Salary ,@Address ,@DepID )
END
GO
munotes.in

Page 76


77 Advanced Web Technologies
Write down your connection string in web.config file.






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.Connecti onStrings["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("@Sa lary",
SqlDbType.Money).Value=txtSalary.Text;
cmd.Parameters.Add("@Address",
SqlDbType.VarChar).Value=txtAddress.Text; munotes.in

Page 77


78 Database Programming In Asp.Net cmd.Parameters.Add("@DepID",
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 result s 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 collec tion 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 advan tages 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 wit h both the table.

munotes.in

Page 78


79 Advanced Web Technologies

The list of properties for DataSet are as shown below: Property Description Container It gets the container for the component CaseSensitive It gets or sets value indicating whether string comparisons with Data Table objects DataSetName It gets or sets the name of the current
DataSet DefaultViewManager It gets a custom view of the data contained
into the DataSet to allow filtering,
searching and navigating data using a
custom DataViewManager DesignMode It gets a value indicating the component is
currently in design mode Events It gets a list of event handlers that are attached to this component ExtendedProperties It gets a collection of customized user information associated with Data Set HasErrors It gets a value indicating the errors in any DataTable objects within the DataSet Tables It gets the collection of tables contained in the DataSet Relations It gets a collection of relation that links tables and allow navigation from parent tables to child tables IsInitialized It gets a value that indicates whether the DataSet is initialized
The list of methods of DataSet are as shown below: Methods Description AcceptChanges It commits all the changes made in the DataSet when it was loaded or when the last changes were accepted munotes.in

Page 79


80 Database Programming In Asp.Net BeginInit It begins the initialization of a DataSet used on a form or by other component Clear It clears the DataSet of any data by removing all rows in the table Clone It copies the structure of the DataSet including Data Table schemas, relations and constraints Copy It copies the structure and data from the DataSet CreateDataReader() It returns the DataTableReader with one
result set per Data Table Dispose() It release all the resources used by the
MarshalByValueComponent EndInit It ends the initialization od a DataSet that is
used on a form Finalize It allows the object to try to free resources
and perform cleanup operations before the
garbage collection GetChanges() It gets a copy of the DataSet containing all changes made in the last load GetDataSetSchema It gets a copy of XmlSchemaSet for the DataSet GetHashCode It serves as a default hash function HasChanges() It gets a value indicating whether DataSet has changes, including new, deleted or modified rows InferXmlSchema(String, String[]) It applies the XML Schema from the specified Stream into DataSer InferXmlSchema(TextReader, String[]) It applies the XML Schema from the specified XmlReader to the DataSet IsBinarySerialized It inspects the format of the serialized representation of the DataSet Load(IDataReader, LoadOption, String[]) It fills a DataSet with values from a data source using supplied IDataReader using array of strings MemberwiseClone It creates a shallow copy of the current Object munotes.in

Page 80


81 Advanced Web Technologies Merge(DataRow[]) It merges an array of DataRow objects into the current DataSet Merge(DataSet, Boolean) It merges a DataSet and its schema into current DataSet Merge(DataTable, Boolean, MissingSchemaAction) It merges a DataTable and its schema into current DataSet preserving or removing changes into the DataSet OnRemoveRelation It occurs when a DataRelation object is removed from the DataTable ReadXml(Stream) It reads XML Schema and data into DataSet using System.IO.Stream Reset It clears all tables and removes all relations, contraints, and tables from the DataSet ShouldSerializeRelations It gets a value indicating the Relations property should be persisted ToString It returns a string containing the name of the component WriteXml(Stream) It writes the current data for the DataSet using the System.IO.Stream WriteXml(TextWriter) It writes the current data for the DataSet using the TextWriter WriteXml(TextWriter, XmlWriteMode) It writes a current data and schema for the DataSet using the TextWriter and XmlWrite mode WriteXmlSchema(XmlWriter) It writes the DataSet structure as an XMl schema to the XmlWriter object
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; munotes.in

Page 81


82 Database Programming In Asp.Net public partial class Default : System.Web.UI.Page
{
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", c onn);
ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch(Exception ex)
{
Label1.Text = "ERROR :: " + ex.Message;
}
finally
{
ds.Dispose();
conn.Dispose();
}
}
}
5.4.4.1 Datatableand Datarow :
The DataTable class is used when the tables of the database are to be
represented. The list of some DataTable properties is as shown below: Property Description CaseSensitive It indicates that the string comparisons are case – sensitive ChildRelations It gets the collection of child relations for this DataTable Columns It gets the collection of columns belonging to the table Constraints It gets the collection of constraints maintained by the table DataSet It gets the DataSet to the corresponding table munotes.in

Page 82


83 Advanced Web Technologies DisplayExpression It gets or sets the expression returning a value to represent the table Events It gets the event handlers list attached to the component Namespace It gets or sets the namespace for the XML representation of the data store PrimaryKey It gets or sets an array of columns functioning as primary key for the table Rows It gets the collection of rows belonging to the
table TableName It gets or sets the name of the DataTable
The list of some of methods of the DataTable are as shown below: Methods Description AcceptChanges It contains all the changes when the last
AcceptChanges was called Clear It clears the DataTable of all data Clone It clones the structure of the DataTable containing constraints and schemas Copy It copies the structure and data for the DataTable Dispose() It releases all the resources used by the MarshalByValueComponent EndLoadData It turns on notifications, constraints, indes maintenance after the data is loaded Finalize It allows an object to free resources and perform cleanup operations before garbage collection GetChanges() It gets a copy of DataTable where all the changes are made by the user ImportRow It copies the DataRow into DataTable Load(IDataReader) It fills a DataTable with values from a data source using IDataReader munotes.in

Page 83


84 Database Programming In Asp.Net Merge(DataTable) It merges the DataTable with the current DataTable NewRow It creates a new row with the schema similar to the DataTable Reset It resets the DataTable to the original state Select() It gets an array of all DataRow objects WriteXml(String) It writes the current contents of the DataTable as XML using the specified file
The syntax of creating DataTable in an application is as shown below: DataTabledt = newDataTable(); DataColumn dc = newDataColumn(); dc.ColumnName = “Srno”; dc.DataType = typeof(int); dt.Columns.Add(dc); DataColumn dc1 = newDataColumn(); dc.ColumnName = “Name”; dc.DataType = typeof(string); dt.Columns.Add(dc1); dt.Rows.Add(newobject [ ] { “1”, “John”});
Datarow :
The DataRow is used to represent rows in the DataTable. Some of the
properties of DataRow are as shown below: Property Description HasErrors It gets a value indicating that row has errors Item[DataColumn] It gets or sets the data stored in the specified DataColumn Item[String] It gets or sets the data stored in the column specified by the name ItemArray It gets or sets all the values for this row through an array RowError It gets or sets the custom error description for a row munotes.in

Page 84


85 Advanced Web Technologies Table It gets the DataTable for DataSet
The syntax for creating DataRow is as shown below:
DataRowdr =newdt.NewRow();
dr[“Name”]=”Mark”;
dr[“Course”]=”MBA”;
dt.Rows.Add(dr);
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 cann ot
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 acce ss the record.
 It is used in Connected architecture.
 Provide better performance.
 DataReader Object has Read -only access.
 DataReader Object Supports a single table based on a single SQL
query of one database.
 While DataReader Object is Bind to a single cont rol.
 DataReader Object has Faster access to data.
 DataReader Object Must be manually coded.
 We can’t create relation in data reader.
 Data reader communicates with the command object.
 DataRea dercan not modify data
For initializing the DataReader object, cal l the ExecuteReader method of
the Command object. It returns an instance of the DataReader.
SqlCommandcmd = new SqlCommand("Your SQL query", conn);
SqlDataReaderreaderObj = cmd.ExecuteReader();
Once your task completed with the data reader, call the Close( ) method to
close the DataReader.
readerObj.Close(); munotes.in

Page 85


86 Database Programming In Asp.Net

DataReader Properties and Methods : Property Description Connection It gets the Connection associated with DataReader Depth Indicates the depth of nesting for row FieldCount Returns number of columns in a row HasRows It gets a value indicating the DataReader has one or
more rows IsClosed Indicates whether a data reader is closed RecordsAffected Number of row affected after a transaction Item Gets the value of a column in native format Methods Description Read() Reads next record in the data reader. NextResult() Advances the data reader to the next result during
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();
}
Difference b etween DataSet and DataReader : DataSet DataReader Works in connected mode. It provides connection oriented environment. Provides slow performance compare to DataReader. Provides the fast execution. In memory object. You can fetch the data in any order. It is a forward-only and read only object. Implicitly open the connection. It needs explicit open and close the connection. munotes.in

Page 86


87 Advanced Web Technologies It can contain more than one table. At a time, it works on single table. Dataset objects have XML Support. It does not fully support XML It uses fill() method of DataAdapter to populate the dataset. DataReader object provides the read() method for reading the 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 writ ing 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 DeleteCommand It is used for deleting records from the data source InsertCommand It is used to insert records in a data source SelectCommand It is used to select records from a stored procedure UpdateCommand It is used to update records in the data source TableMappings It represents the collection of mappings between actual data source table
The list of methods for the DataAdapter is as shown below: munotes.in

Page 87


88 Database Programming In Asp.Net Methods Description Fill It is used to fill data into DataSet using DataAdapter Update It is used to update data to the data source FillSchema It adds a DataTable to the DataSet
5.5 LINQ WITH ASP.NET Language integrated query or LINQ enables you to write SQL like syntax
in programming language itself. LINQ contains different types of
operators, which is used in language itself. In LINQ, the sam e query can
be used in, an SQL database, a DataSet, an array of objects in memory and
so many other data types.
5.5.1 LINQ Introduction:
Architecture of LINQ :
In this chapter, we are going to study the Architecture of LINQ . The
term LINQ stands for Language Integrated Query and it is pronounced
as LINK . Nowadays the use of use LINQ increasing rapidly. So, as a
developer, you should understand the Linq and its architecture.
What is LINQ?
The LINQ (Language Integrated Query) is a part of a language bu t 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 sin gle 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. munotes.in

Page 88


89 Advanced Web Technologies

Fig. 5.4 LINQ Query on Different Data Sources

Why should we learn LINQ?
Let us understand why we should learn LINQ with an example.
Suppose we are developing a .NET Application and that application
requires data from different data sources. For example
1. The application needs data from SQL Server Database. So as a
developer in order to access the data from SQL Server Database, we
need to understand ADO.NET and SQL Server -specific syntaxes. If
the database is Oracle then we need to learn SQL Syntax specific to
Oracle Database.
2. The application also needs data from an XML Document. So as a
developer in order to work with XML Document, we need to
understand XPath and XSLT queries.
3. The application also needs to manipulate the data (objects) in memory
such as List, List , etc. So as a developer we
should also have to understand how to work with in -memory objects.

Fig. 5.5 Data from different data sources
munotes.in

Page 89


90 Database Programming In Asp.Net LINQ provides a uniform programming model (i.e. common query syntax)
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.
How LINQ works?

Fig. 5.6 Working of LINQ
As shown in the above diagram, you can write the LINQ queries using any
.NET supported p rogramming languages such as C#, VB.NET, J#, etc.
The LINQ provider is a software component that lies between the LINQ
queries and the actual data source. The Linq provider will convert the
LINQ queries into a format that can be understood by the underlying data
source. For example, LINQ to SQL provider will convert the LINQ
queries to SQL statements which can be understood by the SQL Server
database. Similarly, the LINQ to XML provider will convert the queries
into a format that can be understood by the XML document.
What are LINQ Providers?
A LINQ provider is software that implements the IQueryProvider and
IQueryable interface for a particular data source. In other words, it allows
us to write LINQ queries against that data source. If you want to create
your custom LINQ provider then it must implement IQueryProvider and
IQueryable interface. Without LINQ Provider we cannot execute our
LINQ Queries.
Let us discuss so me of the LINQ Providers and how they work internally.
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 man y useful operations such as
filtering, ordering, and grouping with minimum code.
LINQ to SQL (DLINQ):
munotes.in

Page 90


91 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 whic h 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 flexib ility 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 provide r 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 que ry
any database such as SQL Server, Oracle, MySQL, DB2, etc. Now, it is
called ADO.NET Entity Framework.
LINQ to XML (XLINQ):
The LINQ to XML provider is basically designed to work with an XML
document. So, it allows us to perform different operations on X ML data
sources such as querying or reading, manipulating, modifying, and saving
the changes to XML documents. The System.Xml.Linq namespace
contains the required classes for LINQ to XML.
Parallel LINQ (PLINQ):
The Parallel LINQ or PLINQ was introduced wit h .NET Framework 4.0.
This provider provides the flexibility of parallel implementation of LINQ
to Objects. The PLINQ was designed in such a way that it uses the power
of parallel programming which targets the Task Parallel Library. So if you
want to execu te your LINQ query simultaneously or parallel on different
processors then you need to write the query using PLINQ.
Advantages of using LINQ?
1. We don’t need to learn new query language syntaxes for different data
sources as it provides common query synta x to query different data
sources.
2. Less code as compared to the traditional approach. That means using
LINQ we can minimize our code.
3. It provides Compile time error checking as well as intelligence
support in Visual Studio. This powerful feature help s us to avoid run -
time errors. munotes.in

Page 91


92 Database Programming In Asp.Net 4. LINQ provides a lot of inbuilt methods that we can use to perform
different operations such as filtering, ordering, grouping, etc. which
makes our work easy.
5. Its query can be reused.
Disadvantages of using LINQ?
The dis advantages 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.
5.5.2 Mapping Data Model To An Object Model :
The LINQ to SQL Object Model
In LINQ to SQL, an object model expressed in the programming language
of the developer is mapped to the data model of a relational database.
Operations on the data are then conducted according to the object model.
In this scenario, you do not issue database commands (for example,
INSERT) to the database. Instead, you change values and execute methods
within your object model. When you want to query the database or send it
changes, LINQ to SQL translates your requests into the correct SQL
commands and sends those commands to the database.

Fig. 5.7 The LINQ to SQL Object Model
The most fundamental elements in the LINQ to SQL object model and
their relationship to elements in the relational data model are summarized
in the following table: LINQ to SQL Object Model Relational Data Model Entity class Table Class member Column Association Foreign-key relationship Method Stored Procedure or Function
munotes.in

Page 92


93 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. Behi nd 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 t he 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.
munotes.in

Page 93


94 Database Programming In Asp.Net

Drag the table in the left pane. If primary key & foreign key rel ations are
there then it will automatically displayed. I have not created the foreign
key explicitly. Therefore the relation is not shown.

This process generates the Emp.dbml.layout and Emp.designer.cs file
under the Emp.dbml
It will also create the conn ection string automatically in web.config file.


providerName="System.Data.SqlClient" />


Click on Emp.designer.cs file, you will see EmpDataContext class that is
inherited from DataContext class. Remember that we have created the
Emp.dbml file and it will generate the EmpDataContext class. Whatever
munotes.in

Page 94


95 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 s ender, 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 ca n 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
fromem p in dbContext.tblEmps
select new{emp.EmpID , emp.Name};

munotes.in

Page 95


96 Database Programming In Asp.Net Controlling column ordering and column name using LINQ :
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;
Insert record using LINQ :
For inserting the record into the database using LINQ, first create the
object of EmpDataContext class.
EmpDataContextdbContext = n ew EmpDataContext();
In our example the table name is tblEmps. LINQ automatically generates
the tblEmps as a class and the table column as properties.
Now create the object of tblEmps class, so you can access the properties of
this class.
InsertOnSubmit() method is used to insert the record. SubmitChanges()
method commits all the changes into the database.
Please refer the previous code for populate the Gridview using LINQ. In
above example we have used LoadData() method for this purpose.
protected void btn Insert_Click(object sender, EventArgs e)
{
using(EmpDataContextdbContext =new EmpDataContext())
{
tblEmpempObj = new tblEmp
{
EmpID=Convert.ToInt32( txtEmpID.Text),
Name=txtName.Te xt,
Gender=txtGender.Text,
Salary=Convert.ToDouble( txtSalary.Text),
Address=txtAddress.Text,
DEPID = txtDepID.Text
}; munotes.in

Page 96


97 Advanced Web Technologies dbContext.tblEmps.InsertOnSubmit(empObj);
dbContext.SubmitChanges();
}
GetData();
}
Update record using LINQ :
For updating the record, first we need a unique ID of employee whose
record we want to update. For getting single record, SingleOrDefault is
used in LINQ. A fter that SubmitChanges() method is used to commit the
updated record in database.
In the given below code, you can easily see that, the table is converted into
the class and the column name is converted into the properties of tblEmps
class.
protected void btnUpdate_Click(object sender, EventArgs e)
{
using (EmpDataContextdbContext = new EmpDataContext())
{
tblEmpobj=dbContext.tblEmps.SingleOrDefault(em =>em.EmpID
== Convert.ToInt32(txtEmpID.Text));
obj.Name=t xtName.Text;
obj.Gender=txtGender.Text;
obj.Salary=Convert.ToDouble( txtSalary.Text);
obj.Address=txtAddress.Text;
obj.DEPID = txtDepID.Text;
dbContext.SubmitChanges ();
}
GetData();
}
Delete record using LINQ :
For deleting the record, we also need a single record according to unique
ID of employee. Here for deletion DeleteOnSubmit() method is used.
protected void btnDelete_Click(object sender, Even tArgs e)
{
using (EmpDataContextdbContext = new EmpDataContext())
{
tblEmpobj = dbContext.tblEmps.SingleOrDefault(em
=>em.EmpID == Convert.ToInt32(txtEmpID.Text));
dbContext.tblEmps.DeleteOnSubmit(obj );
dbContext.SubmitChanges();
}
GetData();
}
In this given example only seven records are available. Here we have
entered an eighth record, when you click on AddRecord button, munotes.in

Page 97


98 Database Programming In Asp.Net btnInsert_Click method will be executed and reco rd is added in the
database.

Getting the actual sql query generated by LINQ :
As you know that SQL server can understand only standard SQL queries
and objects. Therefore LINQ to SQL convert LINQ queries into standard
SQL query format.
You can easily see t he sql query, which is generated by LINQ to SQL.
There are several methods to achieve for the same.
EmpDataContextdbContext = new EmpDataContext();
varselectQuery = from emp in dbContext.tblEmps
select emp;
First Method:
You can use the l og 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());


munotes.in

Page 98


99 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);
5.5.4 Entity Framework :
What is Entity Framework in .NET Framework?
Entity Framework is an open -source object -relational mapper framework
for .NET applications supported by Microsoft. It increases the developer’s
productivity as it enables developers to work with data using objects of
domain -specific classes without focusing on the underlying database
tables and columns where this data is stored. It eliminates the need for
most of the data -access code which is used to interact with the database
that developers usually need to write. It provides an abstract level to the
develo pers to work with a relational table and columns by using the
domain -specific object. It also reduces the code size of the data specific
applications and also the readability of the code increases by using it. This
is a new technology for accessing the dat a for Microsoft application. The
latest version for Entity Framework is 6.0.
The following figure describes where the Entity Framework presents in
your application.

Fig. 5.8 Entity Framework
The above figure represents how an entity framework interacts with the
domain class and database. It provides a connection between the business
entity and data tables in the database. It saves data stored in the properties
of business entities and also ret rieves data from the database and converts
it to business entities objects automatically. Entity Framework will
munotes.in

Page 99


100 Database Programming In Asp.Net execute the relevant query in the database and then materialize results into
instances of your domain objects for you to work within your app.


Fig. 5.9 Conceptual Model
When defining the class and features of entity framework first and then
entity framework convert it into the conceptual model first and it creates
database and objects in the database from the conceptual model this
method is cal led Code First. Now your object directly works with the
database to retrieve or make changes.
Features of Entity Framework :
 It is platform independent.
 It uses LinQ queries to manipulate the data in the database instead of
SQL queries.
 It keeps the track o f values that have been changed of the properties
of entities.
 It also save changes which are done insert, delete or update
operations.
 It also handles concurrency so the data override by a user and will
reflect when another use fetches it.
 It also handles transaction management automatically and also
provides the customize options for transaction management.
 It provides caching which means it stores the result of the frequently
used queries.
 It also follows certain conventions for programming so it by defa ult
configure the EF Model.
munotes.in

Page 100


101 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 L ine Interface).
 It also supports stored procedure.
 It also supports parameterized queries.
5.6 LET US SUM UP This chapter covered features of ADO.NET. These features are designed
to give you the flexibility to handle database processing in a manner never
before possible with either of the previous versions of ADO. We studied
the components of ADO.NET that is Provider, Connection, Command,
Dataset, Datareader and Dataadapter.
The LINQ with ASP.NET,In LINQ to SQL, and an object model
expressed in the program ming language of the developer is mapped to the
data model of a relational database and Query syntax. Entity Framework is
an open -source object -relational mapper framework for .NET applications
supported by Microsoft.
5.7 UNIT END EXERCISES 1) What is ADO. NET?
2) Explain the advantages of ADO.NET.
3) Explain ADO.NET data architecture.
4) Explain different data provider.
5) Explain connection and command with example
6) Explain data adapter and dataset.
7) Explain data grid with example.
8) Explain data reader with example.
9) Explain the architecture of LINQ.
10) What is The LINQ to SQL Object Model?
11) Explain the working of LINQ.
12) Explain the features of Entity Framework.
munotes.in

Page 101


102 Database Programming In Asp.Net 5.8 LIST OF REFERENCES Reference No Reference Name 1 https://www.tutorialspoint.com/asp.net/asp.net_database_access.htm 2 https://www.guru99.com/insert-update-delete-asp-net.html 3 http://asp.net-informations.com/dbpro/asp-dbpro.htm 4 https://www.w3schools.com/asp/webpages_database.asp 5 https://www.geeksforgeeks.org/what -is-entity -
framework -in-net-framework/ 6 https://www.tutorialride.com/asp -net/linq -in-asp-
net.htm






*****

munotes.in

Page 102

103
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 a re 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.
munotes.in

Page 103


104 Databound Controls In Asp.Net 6.2 SQLDATASOURCE CONTROL The SqlDataSource control is used to access data located in the relational
database. It uses the ADO.NET classes to interact with any databases that
are supported by ADO.NET. The providers that can be used are oracle,
SQL server, ODBC and OleDb. Using the control user can access and
manipulate data in the ASP.NET page .
To use the SqlDataSource control, set the ProviderName and
ConnectionString property. The ProviderName is used for the type of
the database used and ConnectionString for the connection to the
database.
The data of the SqlDataSource control can be cached and retrieved in the
application. The caching can be enabled by setting the EnableCaching
property to true. The filter of the SqlDataSource control supports a
FilterExpression property. User can add the selection criteria for filtering
of data.
The SqlData Source control code sample is as shown below:
DataSourceMode=”DataReader”
ConnectionString=”<%ConnectionStrings:EmployeeData%>”
SelectCommand=”Select name from Employee” >

6.3 DA TABOUND CONTROLS Every ASP.NET web form control inherits the DataBind method from its
parent Control class, which gives it an inherent capability to bind data to at
least one of its properties. This is known as simple data binding or inline
data binding .
Simple data binding involves attaching any collection (item collection)
which implements the IEnumerable interface, or the DataSet and
DataTable classes to the DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of
data into their structure through a DataSource control. These controls
derive from the BaseDataBoundControl class. This is called declarative
data binding .
The data source controls help the data -bound controls implement
functionalities such as, sorting, paging, and editing data collections.
The controls capable of simple data binding are derived from the
ListControl abstract class and these controls are:
● BulletedList munotes.in

Page 104


105 Advanced Web Technologies ● CheckBoxList
● DropDownList
● ListBox
● RadioButtonList
The controls capable of declarative data binding (a more complex data
binding) are derived from the abstract class CompositeDataBoundControl.
These controls are:
● DetailsView
● FormV iew
● GridView
● RecordList
6.3.1 Data List Control :
The DataList control is used to display a repeated list of items that are
bound to the control. There are different templates using which user can
design the layout of the control. The template property are mentioned
below: Template Property Description ItemTemplate It contains the HTML elements and controls to render for each row in the data source AlternatingItemTemplate It contains the HTML elements and controls to render once for every other row in the data source SelectedItemTemplate It contains the elements to render when the user selects an item in the DataList control EditItemTemplate It specifies the layout of an item when the edit mode is working HeaderTemplate It contains all the text and controls to be rendered at the beginning of the list FooterTemplate It contains all the text and controls to be rendered at the end of the list SeperatorTemplate It contains all elements to render between each item
A sample code to demonstrate the DataL ist control is as shown below: <%@Page Language=”C#” %> munotes.in

Page 105


106 Databound Controls In Asp.Net

Id: ’ />
name: ’ />
Income: ’ />

” SelectCommand=”SELECT * FROM [footerex]”>

Output is:

6.3.2 Details View Control:
Details view control is used as a data bound control. It is used to render
one record at a time. User can insert, update and delete the record from the
control. Some of the properties of the Detail sView control is as shown
below:
munotes.in

Page 106


107 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#” %> asp.net DetailsView example: how to use DetailsView

DetailsView Example

” Select Command = “SELECT ProductID, ProductName, UnitPrice FROM Products”;

Page 107


108 Databound Controls In Asp.Net BorderColor=”Tomato”>


The output is:

6.3.3 Formview Control:
The FormView control is data bound control but it uses templates version
of the DetailsView control. T he templates are used inside the control for
rendering it on the server. Some of the properties of the FormView control
are as shown below: 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 of FormView control 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
The sample code for the FormView control is as shown below: <%@ Page Languag”C#” AutoEventWireup=”true” CodeFile=”FormView.aspx.cs” Inherits=”FormView” %> munotes.in

Page 108


109 Advanced Web Technologies asp.net FormView: how to use

FormView

” SelectCommand = “SELECT CategoryID, CategoryName, Description FROM Categories”> Product Catogory CategoryID:<%#Eval ( “CategoryID”)%>
CategoryName:<%#Eval ( “CategoryName”)%>
Description:<%#Eval ( “Description” )%>

The code behind file for the control is as shown below:
public partial class FormView: System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e)
{
if(!this.IsPostBack)
{
FormView1.HeaderStyle.BackColor=System.Drawing.Color.SeaGreen;
FormView1.HeaderStyle.ForeColor=System.Drawing.Color.Snow;
FormView1.HeaderStyle.Font.Bold=true;
FormView1.PagerStyle.BackColor=S ystem.Drawing.Color.ForestGreen;
FormView1.PagerStyle.ForeColor=System.Drawing.Color.AliceBlue;
FormView1.RowStyle.BackColor=System.Drawing.Color.Green;
FormView1.RowStyle.ForeColor=System.Drawing.Color.White;
}
}
}
munotes.in

Page 109


110 Databound Controls In Asp.Net Output is:

6.3.4 Gridveiw Cont rol:
The GridView control is used to provide flexibility in working and display
data from the database. The data in the GridView control is displayed in
the tabular format. It has several properties assigned to the control. Some
of the properties are as me ntioned below: 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 orde r 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
munotes.in

Page 110


111 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. T he
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.
munotes.in

Page 111


112 Databound Controls In Asp.Net 5) The source co de for the GridView control is as shown below:
<%@Page Language=”C#” AutoEventWireup=”true”
CodeFile=”binding.aspx.cs” Inherits=”binding” %>

Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1 -transitio nal.dtd”>






Text=”GetData” Width=”123px” />









6) The code behind file contains the following code
protected void Button1_Click(object sender, EventArgs e)
{
SqlConn ection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings
[ “ConnectionString” ].ToString();
con.Open();

SqlCommand cmd = new SqlCommand();
cmd.CommandText = “Select * from deltable”;
cmd.Connection = c on;
DataSet ds = new DataSet();
da.Fill( ds, “deltable”);
GridView1.DataSource= ds;
GridView1.DataBind();
}
The output is:
munotes.in

Page 112


113 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. Th e 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
A sample code for the list control is as shown below:


ListViewControl – how to use ListView control in asp.net






ListView Control Example:
How to Use ListView Control




ConnectionString=”<%$ConnectionStrings :NorthwindConnectionString”
%>”
SelectCommand = “Select ProductID, ProductName From products
Order By ProductId”
>



DataSourceID=”SqlDataSource1” >









munotes.in

Page 114


115 Advanced Web Technologies

ProductID ProductName











Text=’<%#Eval(“ProductID”)%>’>



(“ProductName”)%>’>








Output is:

6.3.6 Repeater Control :
The Repeater control is a data bound control created by using the
templates to display items. The control does not support editing, paging or
sorting of data rendered through the control. The list of templates
supported by the Repeater control are as mentioned below: Templates Description HeaderTemplate It contains all the text and controls to be rendered at the beginning of the list FooterTemplate It contains all the text and controls to be rendered at the end of the list AlternatingItemTemplate It contains the HTML elements and controls to render once for every other row in the data source SeperatorTemplate It contains all elements to render between each item ItemTemplate It contains the HTML elements and controls to render for each row in the data source munotes.in

Page 115


116 Databound Controls In Asp.Net The sample code for the Repeate r control is as shown below:
































Roll No

StudentName

Total Fees

<%#DataBinder.Eval ( Contiane.”DataItem.RollNo”)%>

<%#DataBinder.Eval(Contianer,”DataItem.Name”)%>

<%#DataBinder.Eval(Contianer.”DataItem.Fees”)%>









munotes.in

Page 116


117 Advanced Web Technologies School Records displayed







The code behind file is as shown below:
public part ial 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 :

6.4 LET US SUM UP This chapter covered the concept of data -binding and its different
classif ications in ASP.NET. Data Binding is a necessity while developing
any application and ASP.NET reduces the workload of programmers and
makes it necessary for them to explore more about it.
6.5 UNIT END EXERCISES 1. What is data binding and its types? Explai n with example? munotes.in

Page 117


118 Databound Controls In Asp.Net 2. Define:
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?
6.6 LIST OF REFERENCES Reference No Reference Name 1 https://www.tutorialspoint.com/asp.net/asp.net_database_access.htm 2 https://www.guru99.com/insert-update-delete-asp-net.html 3 http://asp.net-informations.com/dbpro/asp-dbpro.htm 4 https://www.w3schools.com/asp/webpages_database.asp






*****


munotes.in

Page 118

119
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 managemen t 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,
COR S 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 munotes.in

Page 119


120 Session Management use country control techniques. Today, we're going to research kingdom
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 ne t application.
7.2 STATE MANAGEMENT 1. Meaning of State management method is to preserve state of
control, webpage, Item/data and consumer/user within the application.
2. In the state management, a new example of the web page class is
created on every occasion or every time the page is posted to the
server.
3. It approach that everyone information related to the web page and the
controls on the web page would be misplaced with every spherical
ride.
4. It is nothing but the current value of the page or d ata
5. Data want be hold in such styles of situations:
A. While navigating through internet web page
B. web page performs the round trip
Why we need state management? :
We need state management because when the user visit to his/her,
application browse r does the communication with the respective server
which is depending upon their requested functionality.
Using HTTP protocol, the application browser or internet browser
communicates with the server. When the response returns to client then it
is just cl ean up the resources such as data/Object, Allocated Memory,
Session Ids, URL Information.
What are the types of state Management?
State management has two types.
7.2.1 Client -side state management
7.2.2 Server -side state management
7.2.1 CLient-side state management :
In the client -side Management of user or client pages, during the end to
end interaction the information is stored in the user or client system. munotes.in

Page 120


121 Advanced Web Technologies The main benefit of getting this form of state management is that it saves a
tremendous amo unt 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 appli cation .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
7.2.1.1 View State:
View State is the method to hold the Value of the Page and Controls
among round trips.
It is a Page -Level State Management technique. View State is grown to
become on through default and typically serializes the facts in every
manipulate at the web webpage irrespective of whether in reality used
during the put up returned.
View state is property of every webpage which preserve or save value at
the post back time. For the same pages, it is built -in structure for
automatically saving the values between multiple requests. It stored the
page control value as string which is enc oding some hashing technology.
To store the information or data view state use Hidden field in the hashing
and encoding format. View state is not difficult to implement. There are
no server resources are required. It is providing the security which can be
compress.
Steps for view state:
1. Open New Project
2. Click on the web on the left side
3. select the ASP.NET EMPTY WEB Application
4. Now, Click on solution explorer, right click on ADD>New Item>
Web Form>Name it> click on ADD button, after this you will see
following code:
1. <%@ page language= "C#" autoeventwireup= "true" codebehind= "WebForm6.aspx.cs" inherits= "view_state.WebForm6" %> 2. munotes.in

Page 121


122 Session Management 3. 4. 5. 6. 7. 8. 9.

10.
11. User Name:- 12.
13. Password :- 14.
15. 16. 17.
18.
19. 20.
Now right the code like
1. //Declaration of x and y 2. public string x, y; 3. protected void Button1_Click(object sender, EventArgs e) 4. { 5. //TextBox1 and TextBox2 Value is Assigning on the variable a and b 6. x = TextBox1.Text; 7. y = TextBox2.Text; 8. //after clicking on Button TextBox value Will be Cleared 9. TextBox1.Text = TextBox2.Text = string.Empty; munotes.in

Page 122


123 Advanced Web Technologies 10. } 11. 12. protected void Button3_Click(object sender, EventArgs e) 13. { 14. //value of variable a and b is assingning on TextBox1 and Textbox2 15. TextBox1.Text = x; 16. TextBox2.Text =y; 17. } 18.
And execute this code.
You will get, output.
To save the variable in view state:
ViewState[“Subject”]=”Advanced Web Application”;
To retrieve the information in View State:
String value=ViewState[“Subject”];
7.2.1.2. Query string:
Query string is part of the URL, which is passing data or value one to
another or next page
The size of URL is 255 character long for example user entered welcome
page it will display on next page.
Query string is a easy way to bypass some information from one page to
another. The facts cab be without problems pass to 1 web page to ever y
other or to same web page. With query string technique the statistics
exceeded in URL of page request.
For send data to different web page Response.Redirect() approach used
and for retrieve facts from URL use Request.QueryString() approach used.
In Query String method we can despatched price to only desired web
page, and fee will be quickly. So Query string increase the general overall
performance of internet application.
Syntax of the query string:
Response.Redirect(“nextpage.aspx?name=value”);
Retrieve information from other page
Request.QueryString[“name”].ToString();

munotes.in

Page 123


124 Session Management 7.2.1.3. Cookie:
It provides in web application to store the user particular information.
Whenever user or client visit to websites cookies to storing the
preferences.
Cookie is small piece of text information which store the information and
request and pages as they go between the web server and browser.
Cookies are associated with a web site not with specific page hence the
application browser and server will exchang e cookie information.
There two types of Cookies 1. Persistent Cookie and 2. Non -Persistent
Cookie
1. Persistent cookie:
The persistent cookie permanently stored on hard drive of user.
Persistent cookie has expiry date time. This type of cookie permanentl y
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.
2. Non persistent cookie:
This type of cookie does not store permanently on user’s hard drive. It
store whenever user accessing up information the same browser, once the
browser will closed the information will delete automatically.
To read cookie information:
If (Request.Cookie[“Name”]!=null)
{Lable1.Test=Request.Cookies[“Name”]. Value;
}
7.2.1.4. Hidden Field:
It’s not anything new, as all of us understand from HTML programming.
The hidden field is used to hide your client side records. It is not directly munotes.in

Page 124


125 Advanced Web Technologies seen to the client on the client interface; however, we may additionally se e
the value at the source page. So, it is not really helpful if you want to save
sensitive information. It is simply used to shop a small amount of
information that is often altered.
The Hidden fields are Html input control with hidden type that store in t he
Html hidden data
In their value property the hidden field can store one value only. The value
is stored as string and there fore for some types you need use casting.
The following code statistics the employee variety and has a value of
1001.
7.2.2 Server -Side State Management :
In this type of cookie information is store in the memory. About the user
this type of management stores the confidential and sensitive information
and disadvantage is that it uses more storage from the server.
7.2.2.1 Session’s state
7.2.2.2 Application State
7.2.2.3 Cache
7.2.2.4 Profile
7.2.2. 1 Session Sate:
Session state is a time period of time to visit an internet site or website for
a particular person. Session can save the user or client information on a
server . Session is a quality country control features to shop the patron data
on server separately for each consumer.
Session is a best state management features to store the client data on
server separately for each user.
Each and every session has their unique ID. Using cookie this ID is being
stored in the client machine.
By using session ID the server maintains the state of user information.
Without session ID when user makes a request, the ASP is creating
session ID and sends it with every request and respon se to same user.
Syntax of session:
Session[“session_name”]=”Session value”;
Declare session:
Session[“name”]=”IDOL”;
Response.Redirect(“nextpage.aspx”);
munotes.in

Page 125


126 Session Management To retrive the session value:
String myvalue=session[“name”].Tostring();
Response.Write(“Name=”+myval ue);
Mechanism of session Managements are :
1. In Proc mode
2. Out Proc mode
A. Sql Server
B. State Server
7.2.2.2 Application state:
Application state information is global storage mechanism which is used
to store data on server and shared for all clients or users that means data
stored in application state is common for all. In that data can be accessible
from anywhere in the application.
It is stored in memory on server and in the database it faster to storing and
retrieving information. It is cal led application -level state management.
Data member can be declared and defined in global.asax
To save application data
void Session_Start(object sender,EventArgs e)
{
Application.Lock();
Application[“PageCounter”]=(int)Applicatio n[“PageCounter”]+1;
Application.UnLock();
}
To read application data
void Page_Load(object sender, EventArgs e)
{
int Visitors=(int)Application[“PageCounter”];
}
Following events are of Applic ations State Management:
1. Application_Start()
2. Session_Start()
3. Application_Error
4. Session_End munotes.in

Page 126


127 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.
Types of Caching are as following:
1. Output Caching
2. Data Caching
3. Object Caching
4. Class Caching
5. Configuration Caching
7.2.2.4 Profile :
As the applications must have to man age 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 :







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.
7.4 UNIT END EXERCISES 1. Explain the types of state management. munotes.in

Page 127


128 Session Management 2. What is Cache explain it with an example.
3. How does Cookie works?
4. What is client -side state management?
5. What is server -side state management?
7.5 LIST OF REFERENCES  Freeman, Adam. "Pro asp. netmvc 5 platform." Pro ASP.
NET MVC 5 Platform. Apress, Berkeley, CA, 2014. ISBN:
1430265418
 Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wrox Press,
2014. ISBN: 1118794753
 MVC Framework - First Application (tutorialspoint.com)
 Application State in ASP.Net (meeraacademy.com)





*****










munotes.in

Page 128

129
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
8.1 WHAT IS AJAX? In a simple word ajax means asynchronous JavaScript and XML which
used to create communication between client and server without require
postback . The benefit of this faster response to user It is client -side script.
The MVC Framework contai ns built -in support for unobtrusive Ajax. We
can use helper methods to define features. The features are based on
JQuery features.
The desktop and web application have difference i.e. stateless behaviour
of web application.
To enable the unobtrusive AJAX s upport in the MVC application, open
the Web.Config file and set the UnobtrusiveJavaScriptEnabled property
inside the appSettings section using the following code. If the key is
already present in your application, you can ignore this step.

After this, just open common layout file _Layout.cshtml. we will add
JQuery. munotes.in

Page 129


130 Ajax
< script src=”~/Scripts/jquery.unobtrusive -ajax.min. js”
type=”text/javascript”>

8.2 AP PLICATION WITH UNOBTRUSIVE AJAX 1. First create model file:
using System;
namespace MVCAjaxSupportExample.Models

{
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
}
}
Component of Ajax are following :
1. Ajax Control toolkit
2. XMLHHTTPRequest object in JavaScript
3. Using Jquery AJAX
4. Microsoft Ajax Library
5. Ajax server Control

munotes.in

Page 130


131 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 8.3 AJAX CONTROLS 1. Update Panel Control
2. ScriptManager Control
3. ScriptManagerProxy Control
4. UpdateProgress Control
5. Timer
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:





OnClick=”btnwlcome_Click” Text=”Upadate lable!” />



. munotes.in

Page 131


132 Ajax 2. ScriptManager Control:
The ScriptManager manages all ASP.NET AJAX assets on an internet
web page. It renders the AJAX library to the browser and helps partial
page rendering. It additionally manages partial page uploads and provide
get right of entry to internet service method. Without script su pervisor we
can't use AJAX controls at the web page.
Syntax:
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.
4. Update Progress control:
This is used to display the progress of partial -page updates. You can use
one UpdateProgress control to represent the progress of partial -page
updates for the entire page. A lso, you can include an UpdateProgress
control for every UpdatePanel control. You can customize the default
layout and content of the UpdateProgress control to make it more
attractive.
It used during the server asynchronous processing. During the partial -page
update to complete the use of this is to provide information in the graphics
or Text that is displayed. Content inside this element can be an image.text
or similar HTML content.
Example :






Processing…..


munotes.in

Page 132


133 Advanced Web Technologies

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 en tire 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:


ImageUrl=”~/images/contoso.png”/>
ontick=”timer1_Tick”>



8.4 TESTING AN ASP.NET AJAX APPLICATION After you install the Module for ASP.NET Testing on a pc running WAPT
or WAPT Pro Workplace, you may be in a position to test ASP.NET web
sites containing, especially, AS P.NET AJAX UpdatePanel Controls.
ASP requests normally incorporate __VIEWSTATE and
__EVENTVALIDATION parameters which need to be parameterized.
There are 2 approaches to switch these parameters in server response:
1. In the hidden field of the html code of response, or in the following
way:


munotes.in

Page 133


134 Ajax Reference: Testing of ASP.NET Applications (loadtestingtool.com)
It is just the case of ASP.NET AJAX UpdatePanel Controls usage. In both
cases, the Module for ASP.NET Testing will extract __VIEWSTATE and
__EVENTVALIDATION parameters from responses and correctly
parameterize them. This is done automatically by the module, so you will
not need to do any additional wor k and parameterize ASP requests
manually.
When the module finds a new occurrence of __VIEWSTATE
(__EVENTVALIDATION) during recording, it automatically creates
AspViewState (AspEventValidation) variable calculated
using $ViewState ($EventValidation) functi on, for example:

Reference: Testing of ASP.NET Applications (loadtestingtool.com)
The module detects from which response the current __VIEWSTATE
(__EVENTVALIDATION) was extracted, and substitutes the necessary
variable to the corresponding request which uses that __VIEWSTATE
(__EVENTVALIDATION). So, the Module for ASP.NET Testing
automatically finds __VIEWSTATE and __EVENTVALIDATION
parameters in server responses and parameterizes them, so that correct
__VIEWSTATEs (__EVENTVALIDATIONs) are extracted from the
necessary responses and transferred to the corresponding requests.
If this module is not installed and you record ASP requests, then at the end
of recording process you may receive a warning message. It notifies you
that some of requests contain ASP, s o they will not be parameterized
because the module is not installed.
munotes.in

Page 134


135 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 su re 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 Testin g, or try to
parameterize your profiles manually using regular WAPT functions
available without the module.
8.5 GLOBAL ASAX AND WEB CONFIGU The Global.asax, also known as the ASP.NET application file, is located
in the root directory of an ASP.NET applicat ion. This file contains code
that is executed in response to application -level and session -level events
raised by ASP.NET or by HTTP modules.
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 fo cus on writing better JavaScript code and embracing all the
power jQuery has to offer.
8.7 UNIT END EXERCISES 1. Why we need Ajax in MVC?
2. What are the benefits in Ajax?
3. How does the work Ajax?
4. What are the controllers of Ajax?
5. Create one appli cation in Ajax with JQuery.
8.8 LIST OF REFERENCES  Freeman, Adam. Pro asp. netmvc 5 platform." Pro ASP. NET
MVC 5 Platform. Apress, Berkeley, CA, 2014. ISBN: 1430265418 munotes.in

Page 135


136 Ajax  Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wrox Press,
2014. ISBN: 1118794753
 MVC Framework - First Application (tutorialspoint.com)
 Application State in ASP.Net (meeraacademy.com)
 Testing of ASP.NET Applications (loadtestingtool.com)






*****

munotes.in

Page 136

137
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, engineeri ng, 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
functionali ty use in different platforms using protocols. munotes.in

Page 137


138 Web Services And Wcf ● It does not dependants on any language you can we can write web
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.
9.2 WEB SERVICE Where we can use web service :
● In XML (Extensible Markup Language) web service specifies only
the data understanding the application regarding programming
language.
● By using SOAP (Simple Object Access Protocol) communication
between the Services and the application done.
● In WSDL (Web Services Description Languages) a unique method
that is helpful to specify the web services to the other programs.
● With the help of UDDI (University Description, Discovery, and
Integration) can search web service registries.
1. XML stands for extensible Markup Language.
2. It was design ed to store and transferred the data.
3. It was designed for machine as well as human readable.
4. It was self -descriptive.
5. It stores data in plain text format.
6. It also useful to expand and upgrade to new operating system.
XML webservices are registe red so that potential users can find them
easily. We can do with the Universal Discovery Description and
Integration (UDDI).
XML Declaration

Syntax:
1. It is case sensitive.
2. first statement must be XML document munotes.in

Page 138


139 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.
9.2.1 Advantages of Web Services :
1. It always uses the open, textual content -based totally preferred. net
service makes use of all the ones components even they are written in
diverse languages for extraordinary platforms.
2. It provides promotes the modular technique of the programming in
order that the more than one organization can talk with the identical
net service.
3. Internet offerings are clean to put in force however high -priced
because they use the existing infrastructure, and we will repackage
most of the packages because the w eb service.
4. It reduces the price of business enterprise application integration and
Business to business communications.
5. Web offerings are the interoperable enterprise that carries the 100
carriers and sell them interoperability.
9.2.2 Disadvantage of Web Services :
1. One of the limitations of Web Services is that SOAP, WSDL, UDDI
needs to be upgraded.
2. Support for collaboration is the limit of Web Service.
3. Web service limit is also a fee.
4. If we want to use web services in a high -performance environment, in
that case, the web service will slow down.
5. Use of the web service increases traffic to the network.
6. The level of security of Web Services is low.
7. We use a standard procedure to describe the quality of certain web
services.
8. The Web Service level is in draft form.
9. Maintaining intellectual property is a vendor and is the limit of web
service.

munotes.in

Page 139


140 Web Services And Wcf 9.2.3 Examples of web services :
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)

munotes.in

Page 140


141 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.



munotes.in

Page 141


142 Web Services And Wcf Step 5: We have created one method that is add ()


Step 6: Run the method add () by clicking IIS Express.


munotes.in

Page 142


143 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.

Step 9: You can see output.

munotes.in

Page 143


144 Web Services And Wcf 9.2.4 Creating and Consuming an XML WCF Service -Simple and
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 appl ication. 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.
To create client application :
● Get the service contract, bindings, and address information for
service endpoint: -this can be done by service Model Metadata Utility.
● Create a WCF client using that information: -WCF runtime converts
methods into messages send it to service, collect reply from service
for that message return value to that client.
● Call operations by using try and catch block
● Close the WCF objects.so t hat new client object gets a chance to
connect
The mainly reasons to use WCF are Distributed Application and
Interoperable
Distributed Application means do not run -on single system but multiple
systems which are connected over networks.
Interoperable means that an application can consume or connect with
another application, but it does not matter in which platform it is
developed.
Which consist of three parts
● WCF Service: What it is providing.
● WCF Service host: Where is it.
● Service Client: Who is the client of the Service.
WCF Hosting :
Web services that was hosted inside web server such as IIS using http or
Https protocols.
1. IIS munotes.in

Page 144


145 Advanced Web Technologies 2. WAS (Windows process activation services)
3. Self-hosting
4. Windows service
9.2.5 WCF Features :
1. Service Orientat ion: It uses Service -oriented architecture (SOA) on
which web services uses send and receive data.
2. Interoperability: It uses more industry stands for it.
3. Multiple Message Patterns: Different patterns are used like
request/replay pattern, one way mess age, duplex exchange pattern
4. Service Metadata: It is used to automatically generate and configure
clients for accessing WCF services. And published over HTTP and
HTTPS.
5. Security: Message can be encrypted to protect privacy.
6. Multiple Transports a nd Encodings: whenever Messages can be
sent on uses in transport protocols and encodings like HTTP.
7. Reliable and Queued Messages and Durable: Reliable message
uses reliable session and durable message pattern always saved to the
database.
8. Transaction s: WS-Atomic Transactions, Microsoft Distributed
Transaction coordinator and API Transaction
9. AJAX and REST Support: supported XML formats
10. Extensibility: to customize the behaviour of a service
9.2.6 Advantages of WCF:
1. It is interoperable with other services when compared to .Net
Remoting where the client and service must be .Net.
2. It services provide security and reliability in compared to ASMX web
services.
3. In WCF, there is no need to make much change in code fo r
implementing the security model and changing the binding. Instead, it
requires small changes in the configuration.
4. WCF has integrated logging mechanism with this changing the
configuration file settings will provide this functionality. In other
techn ology developer must write the code.

munotes.in

Page 145


146 Web Services And Wcf 9.2.7 Examples of WCF Service :
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 you r WCF service
name.



munotes.in

Page 146


147 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)


Step 3: After Execution we get new window where we have to double
click on our methods that is GetData () and give the values to the
parameter which is right side of the window and press the button invoke. It
shows the information of sender and receiver.

munotes.in

Page 147


148 Web Services And Wcf


Step 4: We have created add() method

munotes.in

Page 148


149 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
munotes.in

Page 149


150 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.
9.5 LIST OF REFERENCES 1) https://www.javatpoint.com/web -services -in-c-sharp
2) https://www.aspsnippets.com/Articles/Simple -database -Web -Service -
Tutorial -in-ASPNet -with-Example.aspx
3) Spaanjaars, Imar. Beginning ASP. NET 4.5. 1: in C# and VB. John
Wiley & Sons, 2014. ISBN: 1861009038
4) MacDonald, Matthew. ASP. NET: The Complete Refe rence.
McGraw -Hill, Inc., 2002. ISBN:
5) https://www.w3schools.com/asp/default.ASP0072125764
6) Spaanjaars, Imar. Beginning ASP. NET 4.5. 1: in C# and VB. John
Wiley & Sons, 2014. ISBN: 1861009038
7) Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wr ox Press,
2014. ISBN: 1118794753
8) Schildt, Herbert. C# 4.0: the complete reference. Tata McGraw -Hill
Education, 2010




*****



munotes.in

Page 150

151
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 a nd 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 In the ultimate couple of years, I was simply randomly going via a
questionnaire section and located out there are numerous questions on
MVC, especially on the novice stage, or beginner degree to ASP.NET you
can say. There are many queries approximately wh ich is first -rate,
webforms or MVC, and if MVC, which version. As there are a few great
articles which are associated with MVC on C# Corner, this newsletter will
brief you about MVC, variations, a pattern software, and solution the
question: Why MVC? munotes.in

Page 151


152 Designing Mvc Application Toda y in case you do marketplace research the decision for for MVC is
massive and it's far growing in numbers. Each and each company these
days desires a MVC developer due to the fact every time a modern -day
mission for development comes, they certainly need t o broaden their
product in MVC. MVC Version 5 has been launched with new abilities
and the popularity of MVC is developing each day.
If your present -day assignment is in webforms and you find it flawlessly
every day, you could say why MVC?
It is important distinguished between the MVC architecture pattern and the
ASP.net MVC framework. The MVC.NET is old. It dates again to 1978
and the Smalltalk task at Xerox PARC —however it has won enormous
reputation today as a pattern for Web programs, for the following reason:
1. User interaction with an MVC application follows a natural cycle: the
user takes an action, and in response the application changes its data
model and delivers an updated view to the user. And then the cycle
repeats. This is a convenient fit fo r Web applications delivered as a
series of HTTP requests and responses.
2. Web applications necessitate combining several technologies
(databases, HTML, and executable code, for example), usually split
into a set of tiers or layers. The patterns that ari se from these
combinations map naturally onto the concepts in MVC.
The ASP.NET MVC Framework implements the MVC pattern and, in
doing so, provides greatly improved separation of concerns. In fact,
ASP.NET MVC implements a modern variant of the MVC pattern that is
especially suitable for Web applications.
MVC works as per following way of the diagram:

Figure 1
USER Controller View Model Communication Updates Presentation Modification Presentationnn munotes.in

Page 152


153 Advanced Web Technologies 10.2 DESIGNING MVC APPLICATION 10.2.1 First application of MVC:
Visual Studio Express contains all of the features we need to create, test
and deploy an MVC Framework application, but some of those features
are hidden away until we ask for them. To enable all of the features, select
Expert Settings from the Visual Studio Tools ------ > Settings menu.
10.2.2 Creating New Asp.Net Mvc Project:
By creating new MVC framework project in Visual studio.
Select New Proje ct from File menu then Open New Project dialog.
You can see in the following diagram, if we select the web templates in
Visual C# section, we will see the Web Application Project template.
Select this Project type.

Figure 2 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Give or set the Name of new project for example PartyInvites and click on
Ok Button to continue.
which will ask us to set the initial content for the ASP.NET project
Select Empty template Check MVC in the Add folders and core
references sectio n.
munotes.in

Page 153


154 Designing Mvc Application

Fig 3 (ref. Pro ASP.NET MVC 5 Adam Freeman)
It will create a basic MVC project with minimal predefined content and it
will be starting point which we can use for all of the examples in this
chapter. Now need to click OK button to create new project.
Note: The other template alternatives/options are intended to provide you
a extra complete starting point for your ASP.NET tasks.
Once the Visual studio creates the project, we will see the number of files
folder in the Solution Explorer window.
Which is th e default project structure for a new MVC project default and
we can be understand the purpose purpose of each of the files and folders
that Visual Studio creates.

Fig 4 (ref. Pro ASP.NET MVC 5 Adam Freeman)
munotes.in

Page 154


155 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.

Fig 5 (ref. Pro ASP.NET MVC 5 Adam Freeman)
When we are finished, need to be sure to stop debugging by closing the
browser window that shows the error, or by going back to
Visual Studio and selecting Stop Debugging from the Debug menu.
As we have just seen, Visual Studio opens the browser to display the
project. The default browser is, of course, Internet.
Explorer, but you can select any browser that you have installed by using
the toolbar shown in Figure 1.5. As the figure shows, we have a range of
browsers installed, wh ich we find useful for testing web apps during
development.

Fig 6 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Now, will create the first controller in the application. Controllers are just
simple C# classes, in which contains multiple public methods, we can ca ll
it action methods. now to add new controller, right click on the Controllers
munotes.in

Page 155


156 Designing Mvc Application folder in the project and select Add -Controller. Please Name this
Controller and click Add.

Fig 7 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Whenever the Add Scaffold dialog ap pears, select the MVC 5 Controller -
Empty Option as following fig 1.7 and Click the Add Button.

Fig 8 (ref. Pro ASP.NET MVC 5 Adam Freeman)
The Add Controller dialog will appear. Set the name to HomeController
and click the Add button. There are several c onventions represented in this
munotes.in

Page 156


157 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.

Fig 9 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Visual Studio will create a new C# file in the Controllers folder called
HomeController.cs and open it for editing. I have listed the default
contents that Visual Studio puts into the class file in. You can see that the
class is called HomeController and it is derived from the Contro ller class,
which is found in the System.Web.Mvc namespace.
Listing 1
using system;
using system.collections.generic;
using system.Linq;
using system.web;
using system.web.Mvc;
namespaces PartyInvites.Controllers
{
public class HomeController:Controller
{
Public ActionResult Index()
{
return View();
}
}
}
MVC is to make a couple of simple changes to the controller class. Edit
the code in the
munotes.in

Page 157


158 Designing Mvc Application HomeController.cs file so that it matches Listing 2. We have highlighted
the statements that have changed so they are easier to see.
Listing 2
using System;
using System.Collections.Generic;
using Sys tem.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

Figure 10(ref. Pro ASP.NET MVC 5 Adam Freeman)
10.3 CREATING SIMPLE DATA -ENTRY APPLICATION WITH VALIDATION: 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 informa tion about the party
2. A form that can be used to RSVP
munotes.in

Page 158


159 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 sta rt 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.csht ml file.
Listing 3.1
@{
Layout = null;
}




Index



@ViewBag.Greeting World (from the view)

We're going to have an exciting party.

(To do: sell it better. Add pictures or something.)





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

Figure 11 (ref. Pro ASP.NET MVC 5 Adam Freeman)
munotes.in

Page 159


160 Designing Mvc Application 10.3.1 Designing A Data Model:
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 de fine 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 a pplication
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 Gue stResponse.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;}
}
}
10.3.2 Linking Action Method:
Now, the application goal is to include an RSVP form, so we need to add a
link to it from my Index.cshtml view, as munotes.in

Page 160


161 Advanced Web Technologies shown in Listing 3.3.
Adding a Link to the RSVP Form in the Index.cshtml File
@{
Layout = null;
} <
!DOCTYPE html>



Index



@ViewBag.Greeting World (from the view)

We're going to have an exciting party.

(To do: sell it better. Add pictures or something.)


@Html.ActionLink("RSVP Now", "RsvpForm")



Html.ActionLink is an HTML helper method. The MVC Framework
comes with a collection of built -in helper methods th at 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 cli cks 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

Figure 12 ref. Pro ASP.NET MVC 5 Adam Freeman)
munotes.in

Page 161


162 Designing Mvc Application 10.3.3 Creating Action Method:
You wi ll 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 sligh tly 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 easi er. munotes.in

Page 162


163 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

Figure 13 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Click the Add button and Visual Studio will create a new file called
RvspForm.cshtml in the Views/Home folder and open it for editing. We
can see the initial contents in Listing 3.5.
This is another skeletal HTML file, but it contains a @modelRazor
expression. As you will see in a moment, this is the key to a strongly typed
view and the convenience it offers.
Listing 3.5.
The Initial Contents of the RsvpForm.cshtml File
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
} <
!DOCTYPE html>



RsvpForm


munotes.in

Page 163


164 Designing Mvc Application





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>



RsvpForm


@using (Html.BeginForm()) {

Your name: @Html.TextBoxFor(x => x.Name)


Your email: @Html.TextBoxFor(x => x.Email)


Your phone: @Html.TextBoxFor(x => x.Phone)



47
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")

munotes.in

Page 164


165 Advanced Web Technologies
}


For each property of the GuestResponse model class, I use an HTML
helper method to render a suitable HTML input control. These methods let
you select the property that the input element relates to using a lambda
expression, like
this:
...
@Html.TextBoxFor(x => x.Phone)
...
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 ha ndy 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 wan t to read
properties from via the @model expression.
Don’t worry if you aren’t familiar with C# lambda expressions. I provide
an overview in next topic, but an alternative to using lambda expressions
is to refer to the name of the model type property as a string, like this:
...
@Html.TextBox("Email")
...
I find that the lambda expression technique prevents me from mistyping
the name of the model type property, because Visual Studio IntelliSense
pops up and lets me pick the property automatically, as shown i n figure 14 munotes.in

Page 165


166 Designing Mvc Application

Figure 15 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Setting starts to URL:
Visual Studio will, in an effort to be helpful, make the browser request a
URL based on the view that is currently being edited. This is a hit -and-
miss feature because it doesn’t work when we are editing other kinds of
file and because we can’t just jump in at any point in most complex web
apps.
To set a fixed URL for the browser to request, select PartyInvites
Properties from the Visual StudioProject menu, select the Web s ection and
check the Specific Page option in the Start Action category, as shown in

Figure 16 (ref. Pro ASP.NET MVC 5 Adam Freeman)
We can see the form in the RsvpForm view when you run the application
and click the RSVP Now link. Figure 17 shows the r esult.

Figure 17 (ref. Pro ASP.NET MVC 5 Adam Freeman)
munotes.in

Page 166


167 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 decid ing 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 appropri ate 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] munotes.in

Page 167


168 Designing Mvc Application public ViewResult RsvpForm() {
return View();
} [
HttpPost]
public ViewResult RsvpForm(GuestResponse guestResponse) {
// TODO: Email response to the party organ izer
return View("Thanks", guestResponse);
}
}
}
Rendering other views:
The second overload of the RsvpForm action method also demonstrates
how to tell MVC to render a specific view in response
to a request, rather than the default view. Here is the relevant statement:
...
return View("Thanks", guestResponse);
...
This call to the View method tells MVC to find and render a view called
Thanks and to pass the GuestResponse object to the view. To crea te the
view I specified, right -click on any of the HomeController methods and
select AddView from the pop -up menu and use the Add View dialog to
create a strongly typed view called Thanks that uses the GuestResponse
model class and that is based on the Emp ty template. (See the Adding a
Strongly Typed View section for step -by-step details if needed).
Visual Studio will create the view as Views/Home/Thanks.cshtml. Edit the
new view
so that it matches Listing 3.8 — the markup you need to add.
Listing 3.8
The Contents of the Thanks.cshtml File
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
} <
!DOCTYPE html>

munotes.in

Page 168


169 Advanced Web Technologies
Thanks



Thank you, @Model.Name!


@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.
}




Figure 18 (ref. Pro ASP.NET MVC 5 Adam Fre eman)
With Validation/Adding Validation:
Without validation, users could enter nonsense data or even submit an
empty form. In an MVC application, validation is typically applied in the
domain model, rather than in the user interface. This
means that it is able to define validation criteria in one place and have it
take effect anywhere in the application that the model class is used.
ASP.NET MVC supports declarative validation rules defined with
attributes from the System.ComponentModel.DataAnnotations
names pace, meaning that validation constraints are expressed using the
standard C# attribute features.
Listing 3.9 shows how to applied these attributes to the GuestResponse
model class.
Applying Validation in the GuestResponse.cs File
munotes.in

Page 169


170 Designing Mvc Application using System.ComponentMo del.DataAnnotations;
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 at tend")]
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 cla ss.
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", gues tResponse);
} else {
// there is a validation error
return View();
}
} munotes.in

Page 170


171 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.ValidationSummar y 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;
}




RsvpForm


@using (Html.BeginForm())
{
@Html.ValidationSummary()

Your name: @Html.TextBoxFor(x => x.Name)


Your email: @Html.TextBoxFor(x => x.Email)


Your phone: @Html.TextBoxFor(x => x.Phone)



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.FalseStri ng}
}, "Choose an option"() munotes.in

Page 171


172 Designing Mvc Application



}


If there are no errors, the Html.ValidationSummary method creates a
hidden list item as a placeholder in the form. MVC makes the placeholder
visible and adds the error messages defined by the validation attributes.
You can see how this appears in Figure 3.12

Figure 19 (ref. Pro ASP.NET MVC 5 Adam Freema n)
Highlighting Invalid Fields :
The HTML helper methods that create text boxes, drop -downs, and other
elements have a handy feature that can be used in conjunction with model
binding. The same mechanism that preserves the data that a user entered in
a form can also be used to highlight individual fields that failed the
validation checks.
When a model class property has failed validation, the HTML helper
methods will generate slightly different HTML. As an example, here is the
HTML that a call to Html.TextBo xFor(x => x.Name) generates when
there is no validation error:
id="Name" name="Name" type="text" value="" />
And here is the HTML the same call generates when the user doesn’t
provide a valu e (which is a validation error because applied the Required
attribute to the Name property in the GuestResponse model class):
munotes.in

Page 172


173 Advanced Web Technologies 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, selec ting 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 fil e to Styles.css

Figure 20 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Click the Add button and Visual Studio will create the Content/Styles.css
file. Set the content of the new file to match listing 3.11
Listing 3.11
The Contents of the Styles.css File
.field -validation -error {color: #f00;}
.field -validation -valid { display: none;}
.input -validation -error {boreder: 1px solid # f00; background -color:free;}
.validation -summary -errors { font -weight: bold; color: #f00;}
.validation -summary -valid { displ ay: none;}
To use this style sheet, add a new reference to the head section of
RsvpForm view.
Just Add link elements to views just as you would to a regular static
HTML file, although , It show you the bundles feature that allows
munotes.in

Page 173


174 Designing Mvc Application JavaScript and CSS style s heets to be consolidated and delivered to the
browsers over a single HTTP request.
Adding the Link Element in the RsvpForm.cshtml File.
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}




RsvpForm


@using (Html.BeginForm())
{
@Html.ValidationSummary()

Your name: @Html.TextBoxFor(x => x.Name)


Your email: @Htm l.TextBoxFor(x => x.Email)


Your phone: @Html.TextBoxFor(x => x.Phone)



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")



}

munotes.in

Page 174


175 Advanced Web Technologies

Figure 21 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Adding Bootstrap to the Index.cshtml File
@{Layout = null;
}





Index




We're going to have an exciting party!


And you are invited



@Html.ActionLink("RSVP Now", "RsvpForm")




munotes.in

Page 175


176 Designing Mvc Application

Figure 21 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Styling the RsvpForm View
Bootstrap defines classes that can be used to style forms. I am not going to
go into detail, but you can see how I have applied
these classes in List ing 2 -22.
Listing 2 -22. Adding Bootstrap to the RsvpForm.cshtml File
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
} <
!DOCTYPE html>






RsvpForm
61



RSVP



@using (Html.BeginForm()) {
@Html.ValidationSummary()
munotes.in

Page 176


177 Advanced Web Technologies



@Html.TextBoxFor(x => x.Name, new { @class = "formcontrol"})



@Html.TextBoxFor(x => x.Email, new { @class = "formcontrol"})



@Html.TextBoxFor(x => x.Phone, new { @class = "formcontrol"})



@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" })


value="Submit RSVP" />

}




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. munotes.in

Page 177


178 Designing Mvc Application These elements are created using HTML helper methods, which means
that there are not statica lly 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"})

Figure 22 (ref. Pro ASP.NET MVC 5 Adam Freeman)
Styling the Thanks View
The last view file to style is Thanks.cshtml and you can see how I have
done this in Listing . You will notice that the markup we have added is
similar to that in the Index.cshtml view. To make an application easier to
manage, it is a good principal to avoid duplicating code and markup
wherever possible and will introduce you to Razor layouts
Appl ying Bootstrap to the Thanks.cshtml File
@model PartyInvites.Models.GuestResponse
@{
Layout = null;
}






Thanks




Thank you, @Model.Name!



@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.
}





Figure 23 (ref. Pro ASP.NET MVC 5 Adam Freeman)
4. Using Automatically Implemented Property:
The regular C# property feature lets you expose a piece of data from a
class in a way that decouples the data from how it is set and retrieved.
Following Listing contains a simple example in a class called of Product,
which added to the Models folder of the
LanguageFeatures project in a class file called Product.cs
Listing
Defining a Property in the Product.cs File
munotes.in

Page 179


180 Designing Mvc Application namespace LanguageFeatures.Models {
public class Product {
private string name;
public string Name {
get { return name; }
set { name = value; }
}
}
}
The property, called Name, is shown in bold. The statements in the get
code block (known as the getter) are performed when the value of the
property is read, and the statements in the set code block (known as the
setter) are performed when a value is assigned to the property (the special
variable value represents the assigned value). A property is consumed by
other
classes as though it were a field, as shown in Listing, which shows an
AutoProperty action method I added to the Home controller.
Consuming a Property in the HomeController.cs File
using System;
using System.Web.Mvc;
using LanguageFeatures.Models;
namespace LanguageFeatures.Controllers {
public class HomeController : Controller {
public string Index() {
return "Navig ate to a URL to show an example";
}
public ViewResult AutoProperty() {
// create a new Product object
Product myProduct = new Product();
// set the property value
myProduct.Name = "Kayak";
// get the property
string productName = myProduct.Name;
// genera te the view
return View("Result",
(object)String.Format("Product name: {0}", productName));
} munotes.in

Page 180


181 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 descr iption;
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 stri ng Description
{
get { return description; }
set { description = value; }
} /
/...and so on...
}
} munotes.in

Page 181


182 Designing Mvc Application 10.4 USING AUTOMATICALLY IMPLEMENTED PROPERTIES Using Automatically Implemented Properties in the Product.cs File :
namespace LanguageFeatures.Models {
public class Product {
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { set; get; }
}
}
Do not define the bodie s of the getter and setter or the field that the
property is backed by. Both of these are done for me by the C# compiler
when the class is compiled. Using an automatic property is no different
from using a regular property;
The code in the action method i n Listing will work without any
modification
Reverting from an Automatic to a Regular Property in the Product.cs File
namespace LanguageFeatures.Models {
public class Product {
private string name;
public int ProductID { get; set; }
public string Name
{
get
{
return ProductID + name;
}
set
{
name = value;
}
}
public string Description {get; set;}
public decimal Price {get; set;} munotes.in

Page 182


183 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.
10.5 USING OBJECT AND COLLECTION INITIALIZER Another tiresome programming task is constructing a new object and then
assigning values to the properti es, as illustrated by Listing which shows
the addition of a CreateProduct action method to the Home controller.
Constructing and Initializing an Object with Properties in the
HomeController.cs File
using System;
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";
}
public ViewResult AutoProperty()
{
// ...statements omitted for brevi ty...
}
public ViewResult CreateProduct()
{
// create a new Product object
Product myProduct = new Product();
// set the property values
myProduct.ProductID = 100;
myProduct.Name = "Kayak";
myProduct.Description = "A boat for one person";
myProduct.Price = 275M;
myProduct.Category = "Watersports"; munotes.in

Page 183


184 Designing Mvc Application return View("Result",
(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.Categor y));
}
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 intList = new List { 10, 20, 30, 40 };
Dictionary myDict = new Dictionary munotes.in

Page 184


185 Advanced Web Technologies {
{ "apple", 10}, {"orange", 20}, {"plum", 30}
};
return View("Result", (object)stringArray[1]);
}
}
}
10.6 USING EXTENSION METHODS Extension methods are a convenient way of a dding methods to classes that
you do not own and cannot modify directly. Listing shows a ShoppingCart
class, which is added to the Models folder in a file called ShoppingCart.cs
file and which represents a collection of Product objects.
The ShoppingCart Cl ass in the ShoppingCart.cs File
using System.Collections.Generic;
namespace LanguageFeatures.Models;
{
public class ShoppingCart
{
public List Products {get; set;}
}
}
This is a simple class that acts as a wrapper around a List of Product
object s
Listing shows the MyExtensionMethods
Models folder in the MyExtensionMethods.cs
file. Listing Defining an Extension Method in the
MyExtensionMethods.cs File
namespace LanguageFeatures.Models
{
public static class MyExtensionMethods
{
public static decimal TotalPrices(this ShoppingCart cartParam)
{
decimal total = 0;
foreach (Product prod in cartParam.Products)
{ munotes.in

Page 185


186 Designing Mvc Application total += prod.Price;
}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
{
new Product {Name = "Kayak", Price = 275M},
new Product {Name = "Lifejacket", Pri ce = 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", munotes.in

Page 186


187 Advanced Web Technologies (object)String.Format ("Total: {0:c}", cartTotal));
}
}
}
10.7 USING LAMBDA EXPRESSION We can use a delegate to make my FilterByCategory method more
general. That way, the delegate that will be invoked against each Product
can filter the objects in any way I choose, as illustrated by Listing, which
shows the Filter extension method I added to the MyExtensionMethods
class.
Listing Using a Delegate in an Extension Method in the
MyExtensionMethods.cs File
using System;
using System.Collections.Generic;
namespace LanguageFeatures.Models;
{
public static class MyExtensionMethods
{
decimal total = 0;
foreach (Product prod in productEnum)
{
total += prod.Price;
}
return total;
}
public static IEnumerable FilterByCategory
(this IEnumerable productEnum, string
categoryParam)
{
foreach (Product prod in productEnum)
{
if (prod.Category == categoryParam)
{
yield return prod;
}
}
} munotes.in

Page 187


188 Designing Mvc Application public static IEnumerable Filter
(this IEnumerable productEnum, Func
selectorParam)
{
foreach (Product prod in productEnum)
{
if (selectorParam(prod))
{
yield return prod;
}
}
}
}
}
Using the Filtering Extension Meth od with a Func in the
HomeController.cs File
public ViewResult UseFilterExtensionMethod() {
// create and populate ShoppingCart
IEnumerable products = new ShoppingCart {
Products = new List {
new Product {Name = "Kayak", Category = "Water sports", 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)
{ munotes.in

Page 188


189 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 products = new ShoppingCart {
Products = new List

{
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 categoryFilter = delegate(Product prod)
{
return prod.Category == "Soccer";
}; munotes.in

Page 189


190 Designing Mvc Application decimal total = 0;
foreach (Product prod in products.Filter(categoryFilter))
{
total += prod.Price;
}
Other forms of lambda expression:
1.prod => EvaluateProduct(prod)
2. (prod, count) => prod.Price > 20 && count > 0
3. (prod, count) => {
//...multiple code statements
return result;
}

10.8 PROGRAMS BASED ON MVC PATTERN 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 fir st-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 separati on 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 becom e 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. munotes.in

Page 190


191 Advanced Web Technologies The A SP.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 thro ugh 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
displ ay 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 versi ons 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 sy ntax entirely.
10.9 FORMS AND HTML HELPERS 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 s hown 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)
{
@str
}
}

munotes.in

Page 191


192 Designing Mvc Application

Index



Here are the fruits: @ListArrayItems(ViewBag.Fruits)


Here are the cities: @ListArrayItems(ViewBag.Cities)


Here is the message:

@Model





Changing the Contents of a Helper Method in the Index.cshtml File...
@helper ListArrayItems(string[] items) {

}
Creating an external helper Method:
Inline helpers are convenient, but they may be used only from the view
wherein they're declared and, if they're too complicated, they could take
over that view and make it tough to read.
The alternative is to create an outside HTML helper technique, that is
expressed as a C# extension method. External helper methods can be used
greater extensively, however are a touch more awkward to put in writing,
due to the fact C# doesn’t certainly take care of HTML element era
elegantly. To display this selection, I delivered an Infrastr ucture folder to
the example task and created a new CustomHelpers.Cs elegance report
inside it. You can see the contents of this document in listing
munotes.in

Page 192


193 Advanced Web Technologies Listing:
The Contents of the CustomHelpers.cs File
using System.Web.Mvc;
namespace HelperMethods.Infrastru cture
{
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.SetInn erText(str);
tag.InnerHtml += itemTag.ToString();
}
return new MvcHtmlString(tag.ToString());
}
}
}
10.10 DEFINING THE MODEL To start with a simple domain model called Product, defined in a class file
called Product.cs, added to the Models folder. You can see the contents of
the new file in Listing.
Listing.
The Contents of the Product.cs File
namespace Razor.Models
{
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; } munotes.in

Page 193


194 Designing Mvc Application public string Category { set; get; }
}
}
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.
10.12 UNIT END EXERCISES 1. Tell us something about views and model?
2. Briefly explain why ASP.NET MVC?
3. What is use of Views in ASP.NET MVC?
4. How does works controller in ASP.NET MVC?
5. What is View Data?
6. What are the helpers in ASP.NET MVC?
10.13 LIST OF REFERENCES ● Freeman, Adam. "Pro asp. netmvc 5 platform." Pro ASP.
NET MVC 5 Platform. Apress, Berk eley, CA, 2014. ISBN:
1430265418
● Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wrox Press,
2014. ISBN: 1118794753
● MVC Framework - First Application (tutorialspoint.com)



*****


munotes.in

Page 194

195
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 e nd Exercises
11.8 List o f 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?
11.1 REDUCE DUPLICATION IN VIEWS In the previous chapters we had learned t hat what is view and their types:
A View, in the context of Model View Controller (MVC) architecture, It is
a software class that contains a template and data from produces a
response for the browser which receive data from the Controller of the
MVC and pa ckages it and present it to the browser for display.
There are many types of views such as custom view engine, Razor view
engine, partial view. To reduce the duplication in views we can use partial
view.
We will often need to use same fragments of Razor ta gs and HTML
markup in several different places in the application. Rather than duplicate
the content, using partial views which are separate view files that content,
fragments of tags and markup that can be included in other views.
In this chapter we can s ee how to create and use partial views? How it is
work and demonstrate the technique available for passing view data to a
partial view. munotes.in

Page 195


196 View Creating Partial View:
1. Just start by creating Partial View called MyPartial
2. Then right click on the View/Shared f older
3. Select Add from popup menu
4. Visual studio will display the Add View dialog window, which you
have seen previous chapters.
5. Set View Name to MyPartial Template to Empty and check the Create
as partial view option, as following figure.

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 th e 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.Part ial(“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
munotes.in

Page 196


197 Advanced Web Technologies
We can cr eate 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, j ust the content and the way it is used.
The Contents of the MyStronglyTypedPartial.cshtml File.
@model IEnumerable


This is the message from the partial view
    @foreach(string str in model)
    {
  • @str

  • }

We us e 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.cs html File
@{
ViewBag.Title = "List";
Layout = null;
} <
h3>This is the /Views/Common/List.cshtml View
@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
munotes.in

Page 197


198 View /Home/List URL, as shown

Partial view using child Action:
Child action are action met hod invoked from within a view. This lets you
avoid repeating controller logic that you want to use in several places in
the application. Child actions as partial views are to views. Whenever we
want to display some data -driven widget that appears on multi ple pages
and contain data unrelated to the main action that is running. As using this
technique in the SportsStore example to include a data -driven navigation
menu on every page, without needing to supply the navigation data
directly from every action met hod. The navigation data was supplied
independently by the child action.
Any action can be use child action. To demonstrate the child action need
to be added new action method to the Home Controller as shown
Adding a Child Action in the HomeController.cs File
using System;
using System.Web.Mvc;
namespace WorkingWithRazor.Controllers
{
public class HomeController:Controller
{
public ActionResult Index()
{
string[] names = { "Apple", "Orange", "Pear" };
return View(names);
}
public ActionResult List()
{
return View();
}
munotes.in

Page 198


199 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

The time is: @Model.ToShortTimeString()


Child actions are called usi ng 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.
Calling a Child Action in the List.cshtml File :
@{
ViewBag.Title = "List";
Layout = null;
}

This is the /Views/Common/List.cshtml View



@Html.Partial("MyStronglyTypedPartial", new [] {"Apple",
"Orange","Pear"})
@Ht ml.Action("Time") munotes.in

Page 199


200 View You can see the effect of the child action by starting the application and
navigating to the /Home/List URL again, as shown in figure.

To call action method in other controller name
@Html.Action("Time", "MyController")
[ChildActionOnly]
public ActionResult Time(DateTime time) {
return PartialView(time);
}
Then can invoke it from view as follows:
(@Html.Action("Time", new { time = DateTime.Now })
In this section, you will find out about the format view in ASP.NET MVC.
An utility may addit ionally contain a selected UI portion that stays the
identical in the course of the utility, together with header, left navigation
bar, right bar, or footer phase. ASP.NET MVC added a Layout view
which incorporates those common UI quantities so that we do not should
write the same code in each page. The format view is the same as the
grasp page of the ASP.NET webform software.
For example, an application UI may additionally include a header, left
menu bar, right bar, and footer segment that remains the same on each
web page. Only the middle phase adjustments dynamically, as shown












HEADER PLACEHOLDER FOOTER RIGHT BAR LEFT BAR munotes.in

Page 200


201 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



@Model.Name
@Model.Price.ToString("c")


@Model.D escription

Now need to update Views/Products/List.cshtml so that it uses the partial
view
Using a Partial View in the List.cshtml File :
@model SportsStore.WebUI.Models.ProductsListViewModel
@{
ViewBag.Title = "Products";
} @
foreach (var p in Model.Products) {
@Html.Partial("ProductSummary", p)
} <
div class="pager">
@Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page
=
x}))
munotes.in

Page 201


202 View

Reference: Pro Asp.Net MVC 5, Adam Freeman
11.3 Pass data values to the view from the controller How to Pass data values to the view from the controller to view:
Through the various ways we can pass the data from the controller to
view. In this chapter we will learn how to interact with Views and
specifically Cover ways we can pass data fro m a controller to View to
render a response to client.
View Bag:
View Bag uses dynamic feature that was added in C# 4.0,
ViewBag=ViewData + Dynamic wrapper around the ViewData
Dictionary.
11.4 GENERATE DIFFERENT CONTENT BASED ON DATA VALUES Pass Data betw een View and Controller:
Steps:
1. Start the Microsoft Visual Studio.
2. Select the New -
Framework) -
-
simple example just Select empty template by check to MVC
3. By right clicking on model folder add model class under solution
explorer
munotes.in

Page 202


203 Advanced Web Technologies 4.

5. Just type code for implementing property automatically and press tab
button which is available on the keyboard twice

6. The model class contain only three properties:
Public Class Result
{
Public int id {get; set; }
Public string ResultName { get; set; }
Public string ResultRecord { get; set; }
}
7. By right clicking on Controlle r folder add controller Class


munotes.in

Page 203


204 View 8. Select an Empty Controller from the list of Scaffold.

9. Give the name your Controller like ResultController . Click on Add.
10. By using ViewBag data can pass from Controller to View.
11. ViewBag: It gets the dynam ic view data.
12. Now create object class and assign it to in ViewBag data dictionary.
Assign the value property based on the class.
13. Public ActionResult Index()
{
Result res= new Result;
Id= ‘97’;
ResultName= “M.Sc.IT”;
ResultDetail= “ The basic Sheet”;
}
ViewBag.Message=res;
}
14. Now add View for an Index by right clicking on it.





munotes.in

Page 204


205 Advanced Web Technologies 15.

Now assign the variable into ViewBag, all properties will be in place
16. Insert the c ode:
@using PassDetainMVC.Models
@{
ViewBag.Title= “Index”;
}

Passing data from controller to View


@{
Var data=ViewBag.Message;
}

Id: @data.Id


ResultName:@data.ResultName


ResultDetail:@ data.ResultDetail


Now build and execute/run the code you will get output.
2. Now passing the data from Controller to View
1. Create object same as above
2. Public Class ResultsController: Controller
{
// Get: Result
Public ActionResult Index ()
{
Results res= new results
{
Id= 97
munotes.in

Page 205


206 View Id= ‘97’;
ResultName= “M.Sc.IT”;
ResultDetail= “ The basic Sheet”;
}
ViewData[“Messag e”]=res;
return View();
}

}
3. Access model class when you are using ViewData
4. @using PassDatainMVC.Models
5. @{
6. ViewBag.Title = "Index";
7. }
8.

Passing Data From Controller To View using
ViewData


9. @{
10. var data = (Record)ViewData["Message"];
11. }
12.

Id: @data.Id


13.

ResultName: @data.ResultName


14.

ResultDetail: @data.ResultDetail


Then build and run the code you will get output.
11.5 ADD A NAMESPACE TO A VIEW How to add namspaces in view :
Unlike many templating engines or interpreted view engines, Razor views
are dynamically compiled at run time into classes and then executed. The
compilation happens the first time the viewis requested, which incurs at a
slight one -time performance cost. The benefit is that the next timethe view
is used, it’s running fully compiled code. If the content of the view
changes, ASP.NET willautomatically recompile the view.
The class that a view is compiled into derives from WebViewPage , which
itself derives fromWebPageBase, which you saw earlier in the section munotes.in

Page 206


207 Advanced Web Technologies “Templated Razor Delegates.” For long -time ASP.NET users, this kind of
derivation should come as no surprise because it is similar to how an
ASP.NET Web Forms page works with its Page base class as well.
You can change the base type for Razor views to a custom class, which
makes it possible for you to add your own methods and properties to
views. The base type for Razor views is defined within the Web.config file
in the Views direc tory. The following section of Web.config contains the
razor configuration.

factoryType=”System.web.Mvc.MvcWebRazorhostfactory,system.Eeb.M
vc”version=3.0.0.0,culture=neutral,PublicKeyToken=31BF3857E45/>









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.
11.7 UNIT END EXERCISES 1. Create one MVC application and create code to reduce the duplication
in view.
2. In the same application specify default layout.
3. Explain with example of steps pass data value to the view from the
controller.
4. Write a steps with an example to add namespace to view in MVC
application.
munotes.in

Page 207


208 View 11.8 LIST OF REFERENCES • Freeman, Adam. "Pro asp. netmvc 5 platform." Pro ASP.
NET MVC 5 Platform. Apress, Berkeley, CA, 2014. ISBN:
1430265418
• Allen, K. Scott, et al. Professional ASP. NET MVC 5. Wrox Press,
2014. ISBN: 1118794753
• MVC Framework - First Application (tutorialspoint.com)




*****
















munotes.in