1. INTRODUCTION
ASP.NET is a .NET Framework technology for creating web
application or web app. It is used to building web pages and web sites
with HTML, CSS, JavaScript and server scripting.
ASP.NET 4 supports three different development models:
• Web Pages
• Web Forms
• MVC (Model View Controller)
12. WEB PAGE -Single pages (SPA) model
Web Pages is the simplest programming model for developing ASP.NET web
pages. It provides an easy way to combine HTML, CSS, JavaScript and server
code:
• Easy to learn, understand, and use
• Built around single web pages
• Similar to PHP and Classic ASP
Classic ASP -- was introduced in 1998 as Microsoft's first server side scripting
language. Classic ASP pages have the file extension .asp and are normally
written in VBScript.
Ex:Facebook is almost an SPA - most interactions don't require loading a new
webpage.
13. WEB FORMS - Event Driven Model
• ASP.NET web forms extend the event-driven model of interaction to
the web applications. The browser submits a web form to the web
server and the server returns a full markup page or HTML page in
response.
• All client side user activities are forwarded to the server for stateful
processing. The server processes the output of the client actions and
triggers the reactions.
14. Problems with Asp.Net Web Forms
• ASP.NET Webform was so successful, why Microsoft thought of
creating ASP.NET MVC.The main problem with ASP.NET Webform is
performance, performance and performance. In web application
there are two aspects which define performance:-
• Response time: - How fast the server responds to request?
• Bandwidth consumption: - How much data is sent ?
15. ASP.NET MVC
MVC is one of three ASP.NET programming models.MVC is a framework
for building web applications using a MVC (Model View Controller)
design:
• The Model represents the application core (for instance a list of
database records).
• The View displays the data (the database records).
• The Controller handles the input (to the database records).
The MVC model also provides full control over HTML, CSS, and
JavaScript.
16. The following figure illustrates the interaction between Model, View and
Controller.
• Model is responsible for
maintaining application data and
business logic.
• View is a user interface of the
application, which displays the
data.
• Controller handles user's requests
and renders appropriate View
with Model data.
17. MVC Version History
Microsoft had introduced ASP.NET MVC in .Net 3.5, since then lots of new features have been added.
The following table list brief history of ASP.NET MVC.
MVC Version Visual Studio .Net Version Release date
MVC 1.0 VS2008 .Net 3.5 13-Mar-09
MVC 2.0 VS 2008, .Net 3.5/4.0 10-Mar-10
MVC 3.0 VS 2010 .Net 4.0 13-Jan-11
MVC 4.0 VS 2010 SP1, .NET 4.0/4.5 15-Aug-12
VS 2012
MVC 5.0 VS 2013 .NET 4.5 17-Oct-13
MVC 5.2 - Current VS 2013 .NET 4.5 28-Aug-14
18. 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 which will be executed when the application starts.
Typically, these would be config files like AuthConfig.cs, BundleConfig.cs, FilterConfig.cs,
RouteConfig.cs etc.
Content--folder contains static files like css files, images and icons files.
Models-- folder contains model class files.
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# or VB.NET code.Views folder includes separate folder for each controllers. For
example, all the .cshtml files, which will be rendered by HomeController will be in View > Home
folder.
Shared --folder under View folder contains all the views which will be shared among different
controllers e.g. layout files.
Web.config-- file contains application level configurations.
19. CONTROLLERS
• A Controller handles incoming URL requests.
MVC routing sends request to appropriate
controller and action method based on URL
and configured Routes.
• All the public methods in the Controller class
are called Action methods.
• A Controller class must be derived
from System.Web.Mvc.Controllerclass.
• A Controller class name must end with
"Controller".
20. ACTION METHOD
• Action method is simply a public
method inside controller which
accepts user’s request and returns
some response.
• All the public methods in the
Controller class are called Action
methods.
• Action method has 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.
21. DEFAULT ACTION METHOD
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new { controller = "Home", action =
"Index", id = UrlParameter.Optional });
Every controller can
have default action
method as per
configured route in
RouteConfig class.
By default, Index is
a default action
method for any
controller, as per
configured default
root as shown
below.
22. ROUTING
• Routing is a pattern matching system
that monitor the incoming request
and figure out what to do with that
request and send response.
• Routing plays important role in MVC
framework. Routing maps URL to
physical file or class (controller class in
MVC).
• Route contains URL pattern and
handler information. URL pattern
starts after domain name.
• Routes can be configured in
RouteConfig class. Multiple custom
routes can also be configured.
23. VIEW
• View is a User Interface which displays data and handles user
interaction.
• Views folder contains separate folder for each controller.
• ASP.NET MVC supports Razor view engine in addition to traditional
.aspx engine.
• Razor view files has .cshtml or .vbhtml extension.
26. MODEL
• Model represents domain
specific data and business logic
in MVC architecture. It maintains
the data of the application.
Model objects retrieve and store
model state in the persistance
store like a database.
• Model class holds data in public
properties. All the Model classes
reside in the Model folder in
MVC folder structure.
27. RAZOR
Razor is one of the view engine supported in ASP.NET MVC. Razor allows you
to write mix of HTML and server side code using C# or Visual Basic. Razor
view with visual basic syntax has .vbhtml file extension and C# syntax has
.cshtml file extension.
View Engine is responsible for rendering the view into html form to the
browser. By default, Asp.net MVC support Web Form(ASPX) and Razor View
Engine. There are many third party view engines (like Spark, Nhaml etc.) that
are also available for Asp.net MVC.
Inline expression:
Start with @ symbol to write server side C# or VB code with Html code. For
example, write @Variable_Name to display a value of a server side variable.
For example, DateTime.Now returns a current date and time.
Ex: <h1>Razor syntax demo</h1>
<h2>@DateTime.Now.ToShortDateString()</h2>
28. RAZOR
Multi-statement Code block:
You can write multiple line of server side code enclosed in braces @{ ... }.
Each line must ends with semicolon same as C#.
@{
var date = DateTime.Now.ToShortDateString();
var message = "Hello World";
}
<h2>Today's date is: @date </h2>
<h3>@message</h3>
Declare Variables:
• Variables are used to store data.
• The name of a variable must begin with an alphabetic character and
cannot contain whitespace or reserved characters.
Declare a variable in a code block enclosed in brackets and then use those
variables inside html with @ symbol.
@{
string str = "";
if(1 > 0)
{
str = "Hello World!";
}
}
<p>@str</p>
29. RAZOR-LOGIC CONDITION & LOOPS
if-else condition:
@if(DateTime.IsLeapYear(DateTime.
Now.Year) )
{
@DateTime.Now.Year @:is a leap
year.
}
else {
@DateTime.Now.Year @:is not a
leap year.
}
Loops:
If you need to run the same
statements repeatedly, you can
program a loop. If you know how
many times you want to loop, you
can use a for loop
@for (int i = 0; i < 5; i++) {
@i.ToString() <br />
}
30. RAZOR-ARRAY
An array is useful when you want to store similar variables but don't want to create a separate variable for each
of them:
@{
string[] members = {"Jani", "Hege", "Kai", "Jim"};
int i = Array.IndexOf(members, "Kai")+1;
int len = members.Length;
string x = members[2-1];
}
<html>
<body>
<h3>Members</h3>
@foreach (var person in members)
{
<p>@person</p>
}
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>
31. • People coming from the asp.net web forms background are used to putting the ASP.NET server control on the page
using the toolbox.
• When we work with ASP.NET MVC application there is no toolbox available to us from where we can drag and drop
HTML controls on the view.
• In MVC, if we want to create a view it should contain HTML code for specifying the mark up. ASP.NET MVC framework
comes with a set of HTML Helper methods.
• These helpers are simple functions that let the developer to specify the type of HTML needed on the view.
• This is done in C#.
• The final HTML will be generated by these functions at the runtime i.e. We don't have to worry about the correctness of
generated HTML.
32. HTML HELPER
• HTML Helper is just a method that returns a HTML string. The string can
represent any type of content that you want. For example, you can use HTML
Helpers to render standard HTML tags like HTML <input>, <button> and <img>
tags etc.
• You can also create your own HTML Helpers to render more complex content
such as a menu strip or an HTML table for displaying database data.
Different types of HTML Helpers
• Inline Html Helpers
• Built-In Html Helpers
Standard Html Helpers
Strongly Typed HTML Helpers
Templated HTML Helpers
33. Inline Html Helpers
These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.
@helper arr(string[] i)
{
<ol>
@foreach(string list in i)
{
<li>@list</li>
}
</ol>
}
@arr(new string[] {"c","c++","c#"})
Built-In Html Helpers
Built-In Html Helpers are extension methods on the HtmlHelper class. The Built-In Html helpers can be divided into three
categories:
• Standard Html Helpers
These helpers are used to render the most common types of HTML elements like as HTML text boxes, checkboxes etc. A list
of most common standard html helpers is given below:
34. HtmlHelper Html Control
Html.ActionLink Anchor link
Html.TextBox Textbox
Html.TextArea TextArea
Html.CheckBox Checkbox
Html.RadioButton Radio button
Html.DropDownList Dropdown, combobox
Html.ListBox multi-select list box
Html.Hidden Hidden field
Password Password textbox
Html.Display Html text
Html.Label Label
Html.Editor Generates Html controls based on data type of
specified model property e.g. textbox for string
property, numeric field for int, double or other
numeric type.
35. A list of most common standard html helpers is given below:
HTML Element Example
• TextBox @Html.TextBox("Textbox1", "val")
Output: <input id="Textbox1" name="Textbox1" type="text" value="val" />
• TextArea @Html.TextArea("Textarea1", "val", 5, 15,null)
Output: <textarea cols="15" id="Textarea1" name="Textarea1" rows="5">val</textarea>
• Password @Html.Password("Password1", "val") or @Html.Password("Password1“)
Output: <input id="Password1" name="Password1" type="password" value="val" />
• Hidden Field @Html.Hidden("Hidden1", "val")
Output: <input id="Hidden1" name="Hidden1" type="hidden" value="val" />
• CheckBox @Html.CheckBox("Checkbox1", false)
Output: <input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" />
<input name="myCheckbox" type="hidden" value="false" />
• RadioButton @Html.RadioButton("Radiobutton1", "val", true)
Output: <input checked="checked" id="Radiobutton1" name="Radiobutton1"
type="radio" value="val" />
• Drop-down list @Html.DropDownList (“DropDownList1”, new SelectList(new [] {"Male", "Female"}))
Output: <select id="DropDownList1" name="DropDownList1">
<option>M</option> <option>F</option> </select>
36. Strongly Typed HTML Helpers
These helpers are used to render the most common types of HTML elements in strongly typed view like
as HTML text boxes, checkboxes etc. The HTML elements are created based on model properties.
The strongly typed HTML helpers work on lambda expression. The model object is passed as a value to
lambda expression, and you can select the field or property from model object to be used to set the id,
name and value attributes of the HTML helper. A list of most common strongly-typed html helpers is
given below:
HTML Element Example
• TextBox @Html.TextBoxFor(m=>m.Name)
Output: <input id="Name" name="Name" type="text" value="Name-val" />
• TextArea @Html.TextArea(m=>m.Address , 5, 15, new{}))
Output: <textarea cols="15" id="Address“
name=" Address " rows="5">Addressvalue</textarea>
• Password @Html.PasswordFor(m=>m.Password)
Output: <input id="Password" name="Password" type="password"/>
• Hidden Field @Html.HiddenFor(m=>m.UserId)
Output: <input id=" UserId" name=" UserId" type="hidden" value="UserId-val" />
38. Templated HTML Helpers
• These helpers figure out what HTML elements are required to render based on
properties of your model class. This is a very flexible approach for displaying data to the
user, although it requires some initial care and attention to set up.
Templated Helper Example
• Display Renders a read-only view of the specified model property and selects
an appropriate HTML element based on property’s data type and
metadata.
Html.Display("Name")
• DisplayFor Strongly typed version of the previous helper
Html.DisplayFor(m => m. Name)
• Editor Renders an editor for the specified model property and selects
an appropriate HTML element based on property’s data type and metadata.
Html.Editor("Name")
• EditorFor Strongly typed version of the previous helper
Html.EditorFor(m => m. Name)
39. CONTROLS
There are only two different kind of controls:
• UserControl
• ServerControl
User Controls are controls built with a designer within a web project . User Controls are controls
that are also known as Client Controls. They typically are only private to a web application (Although
there are ways you can make them available to other projects).
Server Controls are controls that are also known as Web Controls. These are reusable controls that
render their html without the aid of a designer, they are created in a seperate assembly from the
web application, are appropiate for controls which will be used in many different web applications
• Button Controls
• Text Boxes and Labels
• Check Boxes and Radio Buttons
• List Controls
• Radio Button list and Check Box list
• Bulleted lists and Numbered lists
• HyperLink Control
• Image Control
40. Button Controls
ASP.NET provides three types of button control:
• Button : It displays text within a rectangular area.
• Link Button : It displays text that looks like a hyperlink.
• Image Button : It displays an image.
When a user clicks a button, two events are raised: Click and Command. Common properties of the button
control:
Property Description
Text The text displayed on the button. This is for button and link button controls only.
ImageUrl For image button control only. The image to be displayed for the button.
AlternateText For image button control only. The text to be displayed if the browser cannot display the
image.
CausesValidation Determines whether page validation occurs when a user clicks the button. The default is
true.
CommandName A string value that is passed to the command event when a user clicks the button.
CommandArgument A string value that is passed to the command event when a user clicks the button.
PostBackUrl The URL of the page that is requested when the user clicks the button.
41. Text Boxes and Labels
Text box controls are typically used to accept input from the user. A text box control can accept one or more
lines of text depending upon the settings of the TextMode attribute.
Label controls provide an easy way to display text which can be changed from one execution of a page to the
next. If you want to display text that does not change, you use the literal text.
Common Properties of the Text Box and Labels:
Property Description
TextMode Specifies the type of text box. SingleLine creates a standard text box, MultiLIne creates
a text box that accepts more than one line of text and the Password causes
the characters that are entered to be masked. The default is SingleLine.
Text The text content of the text box.
MaxLength The maximum number of characters that can be entered into the text box.
Wrap It determines whether or not text wraps automatically for multi-line text box; default is true.
ReadOnly Determines whether the user can change the text in the box; default is false, i.e., the user
can change the text.
Columns The width of the text box in characters. The actual width is determined based on the
font that is used for the text entry.
Rows The height of a multi-line text box in lines. The default value is 0, means a single line text box.
42. Check Boxes and Radio Buttons
A check box displays a single option that the user can either check or uncheck and
radio buttons present a group of options from which the user can select just one
option.
To create a group of radio buttons, you specify the same name for the GroupName
attribute of each radio button in the group. If more than one group is required in a
single form, then specify a different group name for each group.
If you want check box or radio button to be selected when the form is initially
displayed, set its Checked attribute to true. If the Checked attribute is set to true for
multiple radio buttons in a group, then only the last one is considered as true.
Common properties of check boxes and radio buttons:
Property Description
Text The text displayed next to the check box or radio button.
Checked Specifies whether it is selected or not, default is false.
GroupName Name of the group the control belongs to.
43. List Controls
ASP.NET provides the following controls
• Drop-down list,
• List box,
• Radio button list,
• Check box list,
• Bulleted list.
These control let a user choose from one or more items from the list. List boxes and drop-down lists contain
one or more list items.
Common properties of each list item objects:
Property Description
Text The text displayed for the item.
Selected Indicates whether the item is selected.
Value A string value associated with the item.
SelectionMode Indicates whether a list box allows single selections or multiple selections.
SelectedValue The value of the currently selected item. If more than one item is selected, then the value
of the first selected item. If no item is selected, the value of this property is an empty string ("").
SelectedIndex The index of the currently selected item. If more than one item is selected, then the index
of the first selected item. If no item is selected, the value of this property is -1.
44. Radio Button list and Check Box list
A radio button list presents a list of mutually exclusive options. A check
box list presents a list of independent options. These controls contain a
collection of ListItem objects that could be referred to through the
Items property of the control.
Property Description
• RepeatLayout This attribute specifies whether the table tags or the
normal html flow to use while formatting the list when it is rendered.
The default is Table.
• RepeatDirection It specifies the direction in which the controls to be
repeated. The values available are Horizontal and Vertical. Default is
Vertical.
• RepeatColumns It specifies the number of columns to use when
repeating the controls; default is 0.
45. Bulleted lists and Numbered lists
The bulleted list control creates bulleted lists or numbered lists. These
controls contain a collection of ListItem objects that could be referred
to through the Items property of the control.
Common properties of the bulleted list:
Property Description
BulletStyle This property specifies the style and looks of the bullets, or
numbers.
RepeatDirection It specifies the direction in which the controls to be
repeated. The values available are Horizontal and Vertical. Default is
Vertical.
RepeatColumns It specifies the number of columns to use when
repeating the controls; default is 0.
46. HyperLink Control
The HyperLink control is like the HTML <a> element.
Property Description
ImageUrl Path of the image to be displayed by the control.
NavigateUrl Target link URL.
Text The text to be displayed as the link.
Target The window or frame which loads the linked page.
Image Control
The image control is used for displaying images on the web page, or some alternative text, if the image is not available.
Property Description
AlternateText Alternate text to be displayed in absence of the image.
ImageAlign Alignment options for the control.
ImageUrl Path of the image to be displayed by the control.
47. Server Controls
Server controls are tags that are understood by the server.
There are three kinds of server controls:
• HTML Server Controls - Traditional HTML tags
HTML server controls are HTML tags understood by the server.HTML elements in
ASP.NET files are, by default, treated as text. To make these elements
programmable, add a runat="server" attribute to the HTML element. This attribute
indicates that the element should be treated as a server control.
<form runat="server">
<a id="link1" runat="server">Visit W3Schools!</a>
</form>
• Web Server Controls - New ASP.NET tags
Web server controls are special ASP.NET tags understood by the server.Like HTML
server controls, Web server controls are also created on the server and they
require a runat="server" attribute to work.
<form runat="server">
<asp:Button id="button1" Text="Click me!"
runat="server" OnClick="submit"/>
</form>
• Validation Server Controls - For input validation
48. Validation Server Controls
Validation is important part of any web application. User's input must always be
validated before sending across different layers of the application.
Validation controls are used to:
• Implement presentation logic.
• To validate user input data.
• Data format, data type and data range is used for validation.
Validation Control Description
RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the value of
another input control or to a fixed value
RangeValidator Checks that the user enters a value that falls between two
values
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
49. Web Forms - Navigation
Maintaining the menu of a large web site is difficult and time consuming. In
ASP.NET the menu can be stored in a file to make it easier to maintain. This
file is normally called web.sitemap, and is stored in the root directory of the
web.
In addition, ASP.NET has three new navigation controls:
• Dynamic menus
• TreeViews
• Site Map Path
There are some Namespaces, which are used for above Navigation controls
which are given below:
• Using.System.Web.UI.WebControls.TreeView ;
• Using.System.Web.UI.WebControls.Menu ;
• Using.System.Web.UI.WebControls.SiteMapPath ;
50. The TreeView Control
The TreeView control is used for logically displaying the data in a
hierarchical structure.We can use this navigation control for displaying
the files and folders on the webpage.W can easily display the XML
document,Web.SiteMap files and Database records in a tree structure.
There are some types to generate navigation on webpage
through TreeView control.
• TreeView Node Editor dialog box
• Generate TreeView based on XML Data
• Generate TreeView based on Web.SiteMap data
• Generate TreeView from Database.
51. The Menu Control
The menu control is a Navigation control,which is used to display the site
navigation information .This can be used to display the site data structure
vertically and horizontally.It can be used a binding control as TreeView
control.Means we can easily bind the XML and SiteMap data in menu
control.
The menu control can be used as two types.
• Static menu:- It is used to display the parent menu items and their sub
menu items on the page.Means it is used to display the entire structure of
the static menu.
• Dynamic menu:- It is used to display the static menu as well as dynamic
menu on the site.it Means when user passes the mouse over
the menu then it will appear on the site.
When user passes the mouse over the control ,the data will automatically
appear on the site.we can generate dynamic menu control in two ways:
Generate menu control using Xml Data source
Generate menu control using SiteMap Data source
52. The SiteMapPath Control
The SiteMapPath control is also used to display the Navigation
information on the site.It display the current page's context within the
entire structure of a website.
Skip Navigation Links : Home > Services > Support
53. SCAFFOLDING
Scaffolding involves creating base
templates for code or markup of
project items through an
automated method. The basic
templates thus generated can
then be customized to meet your
exact requirements
56. A real time project is incomplete without Database. Entity framework is an
Object/Relational Mapping (O/RM) framework or ORM tool.In RDBMS world,
we speak in terms of Tables and Columns whereas in .net world (which is an
object oriented world), we speak in terms of Classes, objects and properties.
When we think about any data driven application we end up with following
two things.
• Write code for communicating with database (called Data Access Layer or
Database logic)
• Write code for mapping Database data to object oriented data or vice
versa.
ORM is a tool which will automate these two things. Entity framework is
Microsoft ORM tool.It is an enhancement to ADO.NET that gives developers
an automated mechanism for accessing & storing the data in the database.
57. Entity framework is useful in three
scenarios.
• First, if you already have existing
database.
• Second, you want to focus on your
domain classes and then create the
database from your domain
classes.
• Third, you want to design your
database schema on the visual
designer and then create the
database and classes.
60. Database First Approach
The Database First Approach provides an alternative to the Code First
and Model First approaches. It creates model codes (classes,
properties, DbContext etc.) from the database in the project and those
classes become the link between the database and controller.
• The Database First Approach creates the entity framework from an
existing database. We use all other functionalities, such as the
model/database sync and the code generation.
DbContext is the primary class that is responsible for interacting with
data as object, which includes change tracking, persisting data,
managing relationship, caching ,querying to the database. DbContext
works as a bridge between your domain or entity classes and the
database
62. Code First Approach
Code First approach in entity framework is
used to write POCO classes first and
according to that the database will be
created.
POCO classes - Plain Old C# Object:
Just a normal class, no attributes describing
infrastructure concerns or other
responsibilities that your domain objects
shouldn't have.
64. Model First Approach
Model First approach in entity framework is used to create Entities,
relationships, and inheritance hierarchies directly on the design surface
of EDMX and then it will generate database from it.