ASP.net Notes
ASP.net Notes
Introduction to ASP.NET
Contents
• What is ASP.NET?
• ASP.NET and earlier Web Development platforms
• Seven important facts about ASP.NET
• Web Architecture
• ASP.NET page life cycle
• Validation controls
By : Dr. Vikrant 2
What is ASP.NET?
ASP.NET is a server-side technology for building powerful, dynamic
Web applications and is part of the .NET Framework
By : Dr. Vikrant 3
ASP.NET and earlier web development
platforms
✓ASP.NET features a completely object-oriented programming model,
which includes an event-driven, control-based architecture that
encourages code encapsulation and code reuse.
✓ ASP.NET gives you the ability to code in any supported .NET language
(including Visual Basic, C#, J#, and many other languages that have
third-party compilers)
By : Dr. Vikrant 4
ASP.NET and earlier web development
platforms
✓ASP.NET is also a platform for building web services, which are
reusable units of code that other applications can call across platform
and computer boundaries.
✓ASP.NET is dedicated to high performance. ASP.NET pages and
components are compiled on demand instead of being interpreted
every time they’re used. ASP.NET also includes a finetuned data
access model and flexible data caching to further boost performance.
By : Dr. Vikrant 5
Seven Important Facts About ASP.NET
Fact 1: ASP.NET Is Integrated with the .NET Framework
Fact 2: ASP.NET Is Compiled, Not Interpreted
Fact 3: ASP.NET is Multilanguage
Fact 4: ASP.NET runs inside the CLR
Fact 5: ASP.NET is Object Oriented
Fact 6: ASP.NET is Multidevice and Multibrowser
Fact 7: ASP.NET is Easy to Deploy and configure
By : Dr. Vikrant 6
Web Architecture
PC/Mac/Unix/...
Client
+ Browser
Request:
http://www.digimon.com/default.aspx
Response:
<html>….</html>
By : Dr. Vikrant 7
ASP.NET Page Life Cycle
Srno Stages Description
1. Page request When the page is requested by a user, ASP.NET determines whether
the page needs to be parsed and compiled (therefore beginning the
life of a page)
2. Start Page properties such as Request and Response are set. At this stage,
the page also determines whether the request is a postback or a
new request and sets the IsPostBack property
3. Initialization During page initialization, controls on the page are available and
each control's UniqueID property is set. A master page and themes
are also applied to the page if applicable.
By : Dr. Vikrant 8
ASP.NET Page Life Cycle
Srno Stages Description
5. Postback event handling If the request is a postback, control event handlers are called. After
that, the Validate method of all validator controls is called, which
sets the IsValid property of individual validator controls and of the
page
6. Rendering Before rendering, view state is saved for the page and all controls.
During the rendering stage, the page calls the Render method for
each control, providing a text writer that writes its output to
the OutputStream object of the page's Response property.
7. Unload The Unload event is raised after the page has been fully rendered,
sent to the client, and is ready to be discarded. At this point, page
properties such as Response and Request are unloaded and
cleanup is performed.
By : Dr. Vikrant 9
Validation Controls
• A Validation server control is used to validate the data of an input
control.
• If the data does not pass validation, it will display an error message to
the user.
• Syntax:
<asp:control_name id="some_id" runat="server" />
By : Dr. Vikrant 10
Validation Controls
Validation Server Control Description
RequiredFieldValidator Makes an input control a required field
RangeValidator Checks that the user enters a value that falls
between two values
CompareValidator Compares the value of one input control to the
value of another input control or to a fixed value
RegularExpressionValidator Ensures that the value of an input control matches
a specified pattern
CustomValidator Allows you to write a method to handle the
validation of the value entered
ValidationSummary Displays a report of all validation errors occurred in
a Web page
By : Dr. Vikrant 11
Validation Controls
RequiredFieldValidator: ensures that the required field is not empty. It
is generally tied to a text box to force input into the text box.
Syntax:
<asp:RequiredFieldValidator
ID="rfvusername“
runat="server“
ControlToValidate =“txtUsername“
ErrorMessage=“*“ >
</asp:RequiredFieldValidator>
By : Dr. Vikrant 12
Validation Controls
• The RangeValidator control verifies that the input value falls within a
predetermined range.
• It has three specific properties:
<asp:RangeValidator ID="rvclass“
Properties Description runat="server“
Type it defines the type of the data; ControlToValidate="txtclass"
the available values are:
Currency, Date, Double,
ErrorMessage="Enter your class (6 -
Integer and String 12)"
MinimumV it specifies the minimum MaximumValue="12“
alue value of the range MinimumValue="6“
MaximumV it specifies the maximum Type="Integer">
alue value of the range
</asp:RangeValidator>
By : Dr. Vikrant 13
Validation Controls
• The CompareValidator control compares a value in one control with a
fixed value, or, a value in another control.
• It has specific properties:
Properties Description
Type it specifies the data type
ControlToCompare it specifies the value of the input control to compare
with
ValueToCompare it specifies the constant value to compare with
By : Dr. Vikrant 15
Validation Controls
• The RegularExpressionValidator allows validating the input text by
matching against a pattern against a regular expression. The regular
expression is set in the ValidationExpression property.
• Syntax:
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1“
runat="server“
ErrorMessage="Please Enter Valid Email“
ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*@\w+([- .]\w+)*\.\w+([-
.]\w+)*">
</asp:RegularExpressionValidator>
By : Dr. Vikrant 16
Validation Controls
• The CustomValidator control allows writing application specific
custom validation routines for both the client side and the server side
validation.
• The client side validation is accomplished through the
ClientValidationFunction property. The client side validation routine
should be written in a scripting language, like JavaScript or VBScript,
which the browser can understand.
• The server side validation routine must be called from the controls
ServerValidate event handler. The server side validation routine
should be written in any .Net language, like C# or VB.Net.
By : Dr. Vikrant 17
Validation Controls
• Syntax:
<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ErrorMessage="Password Should not be less than 5 character"
ControlToValidate="txtChoosePwd"
ClientValidationFunction="validateText">
</asp:CustomValidator>
By : Dr. Vikrant 18
Validation Controls
• The ValidationSummary control does not perform any validation but
shows a summary of all errors in the page.
• The summary displays the values of the ErrorMessage property of all
validation controls that failed validation.
• Syntax:
<asp:ValidationSummary
ID="ValidationSummary1"
runat="server"
DisplayMode = "BulletList" />
By : Dr. Vikrant 19
References
1. C .Net Web Developers Guide by Syngress
2. ASP.NET 4.5, Covers C# and VB Codes, Black Book , Kogent Learning
Solutions Inc.
By : Dr. Vikrant 20
Session-14
By : Dr. Vikrant 2
ASP.NET MVC Architecture
• MVC stands for Model, View, and Controller.
• MVC is a standard design pattern
• The ASP.NET MVC framework is a lightweight, highly testable
presentation framework that (as with Web Forms-based applications)
is integrated with existing ASP.NET features, such as master pages
• The MVC framework is defined in the System.Web.Mvc namespace
and is a fundamental, supported part of the System.Web namespace.
By : Dr. Vikrant 3
ASP.NET MVC Architecture
Models.
• Model objects are the parts of the application that implement the
logic for the applications data domain.
• Often, model objects retrieve and store model state in a database.
• For example, a Product object might retrieve information from a
database, operate on it, and then write updated information back to a
Products table in SQL Server.
By : Dr. Vikrant 4
ASP.NET MVC Architecture
View
• View in MVC is a user interface.
• View display model data to the user and also enables them to modify
them.
• View in ASP.NET MVC is HTML, CSS, and some special syntax (Razor
syntax) that makes it easy to communicate with the model and the
controller.
By : Dr. Vikrant 5
ASP.NET MVC Architecture
Controller:
• The controller handles the user request.
• Typically, the user uses the view and raises an HTTP request, which
will be handled by the controller.
• The controller processes the request and returns the appropriate
view as a response.
• Controller is the request handler
By : Dr. Vikrant 6
ASP.NET MVC folder structure
• App_Data : folder can contain
application data files like LocalDB, .mdf
files, XML files, and other data related
files.
• App_Start : folder can contain class files
that will be executed when the
application starts
• Content : folder contains static files like
CSS files, images, and icons files. MVC
application includes bootstrap.css,
bootstrap.min.css, and Site.css by
default.
By : Dr. Vikrant 7
ASP.NET MVC folder structure
• Controllers: folder contains class files for
the controllers. A controller handles
users' request and returns a response.
MVC requires the name of all controller
files to end with "Controller". Eg.
HomeController
• Fonts : folder contains custom font files
for your application.
• Models : folder contains model class files.
Typically model class includes public
properties, which will be used by the
application to hold and manipulate
application data.
By : Dr. Vikrant 8
ASP.NET MVC folder structure
• Scripts folder contains JavaScript or
VBScript files for the application.
• Views folder contains HTML files for the
application. Typically view file is a .cshtml
file where you write HTML and C# code.
The Views folder includes a separate
folder for each controller.
• For example, all the .cshtml files, which
will be rendered by HomeController will
be in View -> Home folder. The Shared
folder under the View folder contains all
the views shared among different
controllers e.g., layout files.
By : Dr. Vikrant 9
ASP.NET MVC folder structure
Configuration files :
• Global.asax : file allows you to write
code that runs in response to application-
level events, such as
Application_BeginRequest,
application_start, application_error,
session_start, session_end, etc.
• Packages.config : file is managed by
NuGet to track what packages and
versions you have installed in the
application.
• Web.config : file contains application-
level configurations.
By : Dr. Vikrant 10
Creating Controllers
• The Controller in MVC architecture handles any incoming URL request
• Controller is a class derived from the base class
System.Web.Mvc.Controller
• Controller class contains public methods called Action methods.
• Controller and its action method handles incoming browser requests,
retrieves necessary model data and returns appropriate responses.
By : Dr. Vikrant 11
Creating the Controller
By : Dr. Vikrant 12
Creating Controller
By : Dr. Vikrant 13
Creating Controller
By : Dr. Vikrant 14
Example : StudentController
By : Dr. Vikrant 15
Example : StudentController
By : Dr. Vikrant 16
Action Methods
• All the public methods of the
Controller class are called Action
methods.
• They are like any other normal
methods with the following
restrictions:
• Action method must be public. It
cannot be private or protected
• Action method cannot be
overloaded
• Action method cannot be a static
method.
By : Dr. Vikrant 17
Different Types Of Action Results In ASP.NET MVC
By : Dr. Vikrant 18
View Result
View result is a basic view result. It returns basic results to view page.
View result can return data to view page through which class is defined
in the model. View page is a simple HTML page.
By : Dr. Vikrant 19
PartialView Result
Partial View Result is returning the result to Partial view page. Partial
view is one of the views that we can call inside Normal view page.
We should create a Partial view inside shared folder, otherwise we
cannot access the Partial view.
By : Dr. Vikrant 21
Redirect to Action Result
Redirect to Action result is returning the result to a specified controller
and action method. Controller name is optional in Redirect to Action
method. If not mentioned, Controller name redirects to a mentioned
action method in current Controller
By : Dr. Vikrant 22
Json Result
public JsonResult GetAllStudents()
{
Json (JavaScript List<Student> students = new List<Student>()
Object Notation) {
new Student
result is a {
significant Action StudentId = 1,
StudentName = "Alex"
Result in MVC. It },
new Student
will return simple {
text file format and StudentId = 2,
StudentName = "Smith"
key value pairs. }
};
By : Dr. Vikrant 23
File Result
File Result returns different file format view page when we implement
file download concept in MVC using file result.
By : Dr. Vikrant 24
Content Result
Content result returns different content's format to view. MVC returns
different format using content return like HTML format, Java Script
format and any other format.
By : Dr. Vikrant 25
References
1. C .Net Web Developers Guide by Syngress
2. ASP.NET 4.5, Covers C# and VB Codes, Black Book , Kogent Learning
Solutions Inc.
By : Dr. Vikrant 26
What is ASP.NET MVC
Asp.Net MVC is a "Web Application Framework", that gives you a powerful
pattern based on the way to build dynamic web applications, that enables
clean separation of concerns and that gives you full control of over markup
Main Advantage:
• Clean separation of concerns
• Fast Performance
Parts of Asp.Net
➢ Web Forms
➢ Introduced in 2009,current version is “ASP.Net 5.2.5”
What is MVC?
MVC is an architectural pattern that dictates you to write the application
code as composition of three major parts.
Model
▪ Data Structure
▪ Business Logic
View Controller
▪ Presentation Logic
▪ Reads Data from the model 2 1
Controller
▪ Defines execution flow
3
▪ Execution starts from controller View Model
▪ Fills data into model object
▪ Pass model objects to view
Why ASP.NET MVC
Advantages
supports "Clean Separation of Concerns".
Support Unit Testing
Supports Dependency Injection
Supports faster performance than ASP.net Web Forms.
No Page Life Cycle,controls,Postback and ViewState
Controllers -Overview
Controller is a class that defines execution flow in MVC application.
Controller receives request from the browser, calls model, calls view
Service Model
Browser & View Model
Create Model
Object
Request
View
View Result
Response
Browser
MVC framework
Controller - Development
Controller is a class
Optionally, it is a public class
Controller should be inherited from “System.Web.Mvc.Controller” class
Controller’s name should have a suffix called “Controller” Ex:
HomeController
}
Action Methods
}
Versions of Asp.Net MVC
Asp.Net Mvc 1
Asp.Net Mvc 2
Asp.Net Mvc 3
Asp.Net Mvc 4
Asp.Net Mvc 5
Asp. Net MVC 1.0
March 2009
Visual studio 2008
.NET 3.5
Features
MVC patterns with ASPX Engine
HTML Helpers
Routing
Unit Testing
ASP.NET MVC 2.0
Visual Stuido 2008,2010
.Net 3.5,4.0
Features
Strongly Typed HTML Helpers
Support for data annotations
October 2013
Visual studio 2012,2013,2015,2017
.Net 4.5,4.5.1 and up
Features
Asp.Net Web Api
Asp.Net Identity
Attribute Based Routing
Filter Overrides
Folder structure
Project Folder
\App_Start Contains the files that need to be executed on the first
request
\App_Data Contains SQL Server LocalDB Database Files
\Controllers Contains all controllers
\Models Contains all models
\Views Contain all views
\Views\web.config Contain configuration settings for all views
\Global.asax Contains application level and session level events
\packages.config Contains the list of NuGet packages currently installed in
the project
Action Result
ActionResult is a class ,that represents “result of an action method”
Asp.Net Mvc recommend to specify action methods’s return type as
“ActionResult”
ActionResult is an abstract class that has severa child classes,you can return
any object of any of the child classes
Action Result
RedirectToRouteResult JsonResult
Type of Action Result
ContentResult :Represents any content with specific content-type
ViewResult :Represents result of a view
FileResult :Represents content of a file
JsonResult :Represents json object/json arrray
RedirectResult :Represents redirection to other website(HTTP 302)
RedirectToRouteResult :Represents redirection to a specific action method
PartialViewResult :Represents the result of partial view
View Engines
View Engine provides a set of syntaxes to writes C#.net code(server side
code) in the view
View Engine is also responsible to render the view as html
ASP.NET MVC supports two types of view engines
ASPX View Engine
Razor View Engine
<% @{
C# code C# code
%> }
ASPX (vs) Razor
<% @{
C# code C# code
%> }
• You can’t write the html tags in the code • You can write the html tags in the code
blocks blocks
Shared Views
return view()
View\Shared
View\Controller2
Controller2 return view()
return view()
Layout Views
Layout views contain “page template", which contains common parts of
the UI ,such as logo,header,menubar side bar etc
@RenderBody() method represents the reserved area for the actual
content of view
Execution Flow: Controller ->view ->Layout view ->Rendered View Result
->Send response to browser
{
Content here
}
_ViewStart.cshtml
It defines the default Layout view of all the views of a folder.
If it is present in “View” folder ,it defines the default Layout view of all views of entire
project
If it is present in “Views\Controllername” folder ,it defines the default layout view of all
the views of same controller only
Flow of Execution: Controller->_viewstart.cshtml of "views” folder ->
“_viewstart.cshtml of “Controller1”
Folder-> View->Layout ->Generate View Result ->Response
View
Controllers
Layout View
View1.cshtml
@{
Views2.cshtml
Layout =“Path of Layout view”
_ViewStart.cshtml
}
_ViewStart.cshtml
Partial View
Partial View is a small view that contains content that can be shared among
multiple views
Can be present in “View\Controllername” folder or in “views\Shared” folder
View1.cshtml PartialView.cshtml
@{Html.RenderPartial();}
Content here
Views2.cshtml
@{Html.RenderPartial();}
View (vs) partial View
Employee/details/{empld}
Employee/details/101
Employee/details/102
Employee/details/103
Routing table
Request URL
Routing Engine
public class View Model public class Domain Model public class server Model
{ { {
public datatype public datatype public datatype
propertyname{get;set;} propertyname{get;set;} propertyname{get;set;}
} } }
Request ActionMethod
/Student/Edit?id=1
public ActionResult Edit(int id)
{
Model Binder
}
Model Binding
Bind Attribute
The [Bind] Attribute allows you to specify the list of properties that you want
to bind into the model object, that is received using “Model Binding”
It allows you to specify “Include “ and Exclude “ comma-separated list of
properties
Form
Pu
Model class
StudentId: 1 public class Student
{
Name: abc public int Student ID {get;set}
public string Studentname {get;set;}
}
Model Binding
Action Method
Server Browser(client)
HtmlActionLink Hyperlink
HtmlTextBoxFor Texbox
HtmlTextAreaFor TextArea
HtmlCheckBoxFor Checkbox
HtmlradioButtonFor RadioButton
HtmlListBoxFox Dropdown
HtmlLableFor label
}
Data Annotations for validations
[Required] Field is mandatory
[Maxlength] Maximum no of characters
[Minlength] Minimum no of characters
[Range] value should be within the min and max
[Compare] Two fields must be same
[RegularExpression] Pattern of value
[EmailAddress] Email address only accepted
HTML Helper for Client side Validations
HTML Helper:
ValidationMessageFor :Displays error message
ValidationSummary :Displays validations
summary
Custom Validations
Used to implement user-defined validations
Create a class that extends validationsAttribute class
IsValid method executes after submitting the
form(after Model Binding)
Isvalid method receives the input value as argument
ValidationContext provides details about current
model property’s details
Is Valid method return either”Success” or
“validationResult with error message”
Filters
Filters Execute at a specific situations ,while executing an action
method
Authentication Filters
Executes first ,before any other filter ,to check whether the use is a
valid user or not
Implemented using IAuthenticationFilter
Action Filter
Executes before and after of action method execution, You can
modify the ViewBag,before sending it result
Implemented using IActionFilter
Result Filter
Executes ebfore and after of result execution. You can modify the
result
Implemented using IResultFilter
Built-in Filters
Authorization Filters
[ChilActiononly]
[ValidateAnitForgeryToken]
[Authorize]
Action Filters
[ActionName]
[NonAction]
[HttpGet]
[OutPutCache]
Result Filters
(No Filters)
Exception Filters
[HandleError]
▪Entity Framework (EF) is a database technology ,which is built based on
ADO.NET ,that supports ORM(Object-Relational Mapping) pattern
▪It bridges between “Object Oriented Programming and ‘relational
databases", using Model Classes
Class Modelclass
{ Table:tablename
Public Proertyname{get;set;} -column1
Public Propertyname{get;set; Associate -column2
…
}
Object-Relational mapping ORM
Class Employee
{ Table Employee
public int EmpID {get;set;} {
public string EmpName -EmpID int,
Associate
{get;set;} -EmpName
… svarchar(200)
}
}
Features of EF
Modeling
Querying
Change tracking
Saving
Concurrency
Transactions
Caching
EF Work Flow
EF
Property 1
Property 2 Convert data Object
Property 3 into Object(or) (or)Collection
DB Collection
EF
Query/Non Query Presentation
Logic
Get Result
SaveChanges()
Data(data
-or-
Reader) Read & Print
ToList()
data to the
user
EF EF
Mapping
Conceptual Model Storage Model
Using Modelclassname;
Class Classname:DbContext
{
public Dbset<Modelclass>class{get;set;}
public Dbset<Modelclass>class{get;set;}
}
WINDOWS COMMUNICATION
FOUNDATION
WHAT IS WCF?
– Can be customized
Custom binding
TYPES OF BINDINGS
BasicHttpBinding
WSHttpBinding
WS2007HttpBinding
WSDualHttpBinding
TYPES OF BINDINGS
WSFederationHttp Binding
WS2007FederationHttpBinding
NetTcpBinding
NetNamePipeBinding
NETMSMqBinding
CONTRACTS
Defines what a service communicate
• Service Contracts
– Describe the operations a service can perform
– Map CLR types to WSDL
• Data Contracts
– Describes a data structure
– Maps CLR types to XSD
• Message Contracts
– Defines the (application specific) structure of
the message on the wire
– Maps CLR types to SOAP messages
CONTRACTS
Service Contracts
Describe which operations the client can perform on
the service.
Data Contracts
Define which data types are passed to and from the
service. WCF defines implicit contracts for built-in
types such as int and string, but you can easily
define explicit opt-in data contracts for custom types
CONTRACTS
Fault Contracts
Define which errors are raised by the service, and
how the service handles and propagates errors to its
clients
Message Contracts
}
DATA CONTRACTS
➢ [DataContract] –Specifies type as a data
contract
➢ [datamember] –Members that are part of
contract
[DataContract]
Public class Customer
{ [DataMember]
public bool MyFlag { get; set;}
[DataMember]
public string mystring {get; set;}}
[DataMember]
public string mystring {get; set;}}
BEHAVIOR
Using System;
Using System.Web.Http
namespace namespacename
{
public class controllername:ApiController
{
public returntype Methodname()
{
return value;
}
}
}