Developing ASP - Net MVC4 Applications
Developing ASP - Net MVC4 Applications
NET MVC 4
Overview of Microsoft Web Technologies
WebMatrix 2 - You can use WebMatrix 2 to create static HTML pages and dynamic pages with
ASP.NET, PHP, and Node.js. WebMatrix 2is a free development tool that you can install by
downloading and using the Microsoft Web Platform Installer (Web PI) from the Microsoft website.
WebMatrix2 enables you to develop custom websites based on popular web applications such as
Orchard, Umbraco CMS, and WordPress. Using WebMatrix 2, you can create ASP.NET Web Pages
applications, but not ASP.NET Web Forms or MVC applications
Web Pages: Pages contain server code (C# code, pages have a .cshtml file extension, VB
- .vbhtml). This programming model is simple and easy to learn, and is suited for simple
data-driven sites. ASP.NET 4.5 includes Web Pages version 2.0.
Web Forms: Very similar to building desktop applications. Supports usage of predefined
set of controls that can be dragged and dropped on the form, data source can also be
assigned by drag and drop.
You can also add third-party controls or build custom controls. To respond to user actions,
you can attach event handlers containing code to the server-side controls.
Model
Classes that represent the data or the business logic. Model classes are also
responsible for writing and reading the data to the database.
Controller
Handles user interaction and requests, creates and modifies model classes, and
selects appropriate views.
View
Used to visualize the UI controls and to display them to the users. Controllers
often pass an instance of a model class to a view. The view displays properties of
the model class.
Configuration
Using web.config files, you can configure your web application, regardless of the programming
model. In code, you can access the configuration through the System.Web.Configuration
namespace.
Caching
ASP.NET caches a rendered page in memory, so that it can return the same page to subsequent
user requests without having to render it again from the start. In a similar manner, .NET
Framework objects can also be cached.
You can access cached pages by using the System.Runtime.Caching namespace and configure
the caches in web.config.
Scaling Up IIS
A single web server has limited scalability because it is limited by its processor speed, memory,
disk speed
Furthermore, single web servers are vulnerable to hardware failures and outages.
You can improve the scalability and resilience of your website by hosting it on a multiple server
farm. In such server farms, many servers share the same server name.
All servers can respond to browser requests. A load balancing system such as Windows Network
Load Balancing or a hardware-based system such as Riverbed Cascade, distributes requests
evenly among the servers in the server farm. If a server fails, other servers are available to
respond to requests, and thereby, the website availability is not interrupted.
Perimeter Networks
Web servers, including IIS, are often located on a perimeter network (firewall to the outside
allowing only certain ports and requests to access the IIS server, second parameter is to the
inside network allowing only web application to access resources e.g. database etc).
IIS Express
Internet Information Server 8.0 Express does not provide all the features of Internet Information
Server 8.0 on Windows Server 2012. E.g. you cannot create load-balanced server farms by using
Internet Information Server 8.0 Express.
It has all the features necessary to host rich ASP.NET 4.5 websites and other websites on a single
server. It is included with Windows 8.
In Web Forms applications, you can easily display data by binding controls to data sources. Drag
and drop is supported.
Controls can add large amounts of markup and state information to the rendered HTML
page. This increases the time it takes to load pages.
Why should you be concerned about the markup and state information that ASP.NET Web Forms
controls add to a rendered HTML page?
MVC Applications
ASP.NET 4.5 includes MVC version 4.0.
Models
Models are representation of data and they are implemented as custom .NET classes and store
code in .cs files.
Views
Views create the user interface.
Views are markup pages that store both HTML and C# code in .cshtml files. This means that they
are like Web Pages, but they include only user interface code. Other logic is separated into
Models and Controllers.
Controllers
Controllers respond to user actions, load data from a model, and pass it to a view, so that it will
render a webpage. Controllers implement input logic and tie Models to the right Views.
Controllers are .NET classes that inherit from the System.Web.Mvc.Controller class and store
code in .cs files.
You can configure ASP.NET sites by creating and editing web.config files. The web.config file in the
root folder of your site configures the entire site, but you can override this configuration at lower
levels by creating web.config files in sub-folders.
If you need to access configuration values at runtime in your server-side .NET code, you can use
the System.Web.Configuration namespace.
Authentication
ASP.NET supports several mechanisms for authentication. If you are using Internet Explorer on a
Windows computer, ASP.NET may be able to use Integrated Windows authentication. In this
mechanism, your Windows user account is used to identify you.
For Internet sites, you cannot be sure that users have Windows, a compatible browser, or an
accessible account, so Forms Authentication is often used. Forms Authentication is supported by
many browsers and it can be configured to check credentials against a database, directory
service, or other user account stores.
State Management
Web servers and web browsers communicate through HTTP. This is a stateless protocol - any
values from previous requests are not automatically remembered.
However, when you build a web application, you must frequently preserve values across multiple
page requests.
ASP.NET provides several locations where you can store values or state information across
multiple requests.
Caching
An ASP.NET page is built dynamically by the ASP.NET runtime on the web server. For example, in
a Web Pages application, the runtime must execute the C# code in the page to render HTML to
return it to the browser. That C# code may perform complex and time-consuming operations.
You can use the ASP.NET page cache to store the rendered version of a commonly requested page
in the memory of the web server.
Can you think of other facilities that all ASP.NET applications might need, regardless of the
programming
model they use?
<h2>Details</h2>
<fieldset>
<legend>Comment</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Subject)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Subject)
</div>
<div class="display-label">
Best Practice: Use Web Forms when you want to create a user interface by dragging controls
from a tool box onto each webpage or when your developers have experience of Web Forms or
Windows Forms.
Best Practice: Use MVC when you want the most precise control of HTML and URLs, when you
want cleanly to separate business logic, user interface code, and input logic, or when you want to
perform Test Driven Development.
SSL or HTTP
By default, session state uses cookies to identify users but you can configure ASP.NET to store
session state without using cookies.
Profile propertie
If your site uses an ASP.NET profile provider, you can store user preferences in profiles. Profile
properties are persisted to the membership database so they will be kept even if the web
application or web server restarts.
Database tables
If your site uses an underlying database, like most sites do, you can store state information in its
tables. This is a good place to store large volumes of state data that cannot be placed in server
memory or on the client computer.
Bear in mind that state data is only one form of information that an ASP.NET application places in
server memory. For example, caches must share memory with state data.
Question: You show the visitors of your website a choice of countries. When they pick a state,
you want to redirect them to a page that shows a map of that state. You will not use the name of
the chosen country that the user selected after this. Which location should you use to store the
name of the chosen country?
When you identify the model classes that you will implement in your website, you must also
consider the relationships between them. (one to many, one to one, cascading delte)
Entity Framework
The Entity Framework is an Object Relational Mapping (ORM) framework for the .NET Frameworkbased applications. An ORM framework maps database tables and views to classes that a
developer can program against by creating instances or calling methods. The Entity Framework
has been a part of ADO.NET since the .NET Framework 3.5.
When you use the Entity Framework in your MVC web application, it maps tables or views to the
model classes that you have planned. You do not need to write SQL code to query or update
database tables because the Entity Framework does this for you. The Entity Framework is well
integrated with the Language Integrated Query (LINQ) query language.
If you plan to use the Entity Framework for data access, you should decide on how the database
will be created during the planning phase:
Database-First: Use the Entity Framework in the database-first mode when you have a
preexisting database to work with. This may happen because you already have data from
an earlier system or because a DBA has designed the database for you. You can also
choose this mode if you are familiar with creating databases in a database administration
tool, such as Microsoft SQL Server Management Studio. When you use this mode, you
have to specify the database connection string. The Entity Framework connects to the
database and examines the database schema. It creates a set of classes for you to use for
data access.
Model-First: Use the Entity Framework in the model-first mode when you do not have a
preexisting database and prefer to design your model in Visual Studio. You can use the
Entity Designer tool to name, configure, and link your model classes. This creates XML
files which the Entity Framework uses both to create model classes and to create the
database with its tables and relationships.
Code-First: Use the Entity Framework in the code-first mode when you have no preexisting database and prefer to design your models entirely in C# code. Your code must
include DBContext and DBSet objects these correspond to the database and its tables.
When you run the application for the first time, the Entity Framework creates the
database for you. TODO: Does it create it for the other models if we drop the database?
The Entity Framework lets you work in the Agile or Extreme Programming styles. For example, the
framework can update the database when the model changes. Alternatively the framework can
update the model when the database changes. The Entity Framework can perform these updates
in any Entity Framework mode.
Designing Controllers
Identify Controllers and Actions
In an ASP.NET MVC web application, there is usually one controller for each model class.
Conventionally, if the model class is called Photo, the controller is called PhotoController.
If you follow this convention in your design, you can use the MVC default routing behavior to
select the right controller for a request.
For each controller there can be many actions each action is implemented as a method in the
controller and usually returns a view. You often require separate actions for GET and POST HTTP
request verbs. Similar to designing a model, you can identify the actions to write in each
controller by examining the use cases you gathered during analysis.
Designing Views
Views, Template Views, and Partial Views
There is a many-to-one relationship between MVC controllers and views.
For example, a controller may use one view to display a single photo, another view to display
several photos, and a third view to enable users to upload new photos. Each view corresponds to
a web page that the application can display to the user, although it can display different data. For
example, the PhotoDetails view can display different photos, depending on the ID parameter that
is passed to it.
As you plan views, you should also consider parts of the user interface that appear on all pages.
For example, the company logo, main site menu, links to legal information, and log on controls
may need to appear on every page. You can place these user interface components in a template
view to create a consistent look and feel across pages.
Note: Template views in ASP.NET MVC web applications perform the same role as master pages
in
ASP.NET Web Forms applications.
Some user interface components do not appear on all pages but are reused on several pages. For
example, comments may be displayed in a single photo display, on the gallery, or on other
pages. By creating a partial view, you can create a reusable user interface element that can
appear in many locations in this manner, without duplicating code.
Review Question(s)
Question: You want to support both English and Spanish on your web application. You have both
Spanish-speaking and English-speaking developers and want to ensure that views remain
readable as easily as possible. Should you use multiple view files or multiple resource files to
globalize your site?
Notice that the model class does not inherit from any other class. Also, notice that you have
created public properties for each property in the model and included the data type, such as
integer or string in the declaration. You can create read-only properties by omitting the set;
keyword.
The Photo class includes a property called Comments. This is declared as a collection of
Comment objects and implements one side of the relationship between photos and comments.
The following lines of code illustrate how you can implement the Comment model class.
public class Comment
{
public int CommentID { get; set; }
public int PhotoID { get; set; }
public string UserName { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public virtual Photo Photo { get; set; }
}
Notice that the Comment class includes a PhotoID property. This property stores the ID of the
Photo that the user commented on and ties the comment to a single photo. Also, notice that the
Comment class includes a Photo property, which returns the Photo object that the comment
relates to. These properties implement the other side of the relationship between photos and
comments.
// this is how the Model is instantiated from the controller
Photo newPhoto = new Photo();
newPhoto.Title = "This is an Example Photo";
newPhoto.Owner = User.Identity.Name;
newPhoto.CreatedDate = DateTime.Today;
return View("DisplayView", newPhoto);
The access levels of the property, for example, the get and set keywords to indicate read
and write access.
Additionally by using attributes, you can supply additional metadata to describe properties to
ASP.NET MVC. The MVC runtime uses this metadata to determine how to render each property in
views for display and editing. These attributes are called display and edit annotations.
E.g. DisplayName annotation property names in C# cannot contain spaces, use DisplayName
to provide name containing spaces.
If you have a DateTime property, you can use display and edit data annotations to inform MVC
what format you want the property displayed in.
[DisplayName("Created Date")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime CreatedDate { get; set; }
All the data annotations that are provided with ASP.NET MVC 4 are included in the
System.ComponentModel.DataAnnotations namespace.
Additional Reading: To read more about all the data annotations provided with MVC
4, see http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx
Question: In the code on the slide, how can you recognize the display and edit annotations and
distinguish them from other code?
Note: You will see how to ensure that the validation error message is displayed in a view.
Additional Reading: For more examples of validation data annotations see:
http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-dataannotationvalidators-cs
Additional Reading: For more information about the regular expressions that you can use to
check user input, see: http://msdn.microsoft.com/en-us/library/hs600312.aspx
Question: You want to make sure that users enter a password that is longer than 6 characters.
How could you do this by using a validation data annotation?
To understand the default model binding process, consider the following request from a web
browser:
http://www.adventureworks.com/product/display/45
This request identifies three aspects:
The model class - a product.
The operation to perform on the model class should be displayed.
The specific instance of the model class - ID 45 is
The request is received by an object called the controller action invoker. The controller action
invoker of the MVC runtime calls a controller action and passes the correct parameters to it.
The ControllerActionInvoker class is the default action invoker. This action invoker uses model
binders to determine how parameters are passed to actions.
c. Query Strings: If the user request includes named parameters after a question mark, you can
find these parameters in the Request.QueryString collection.
d. Files: If the user request includes uploaded files, these can be used as parameters.
Notice that if there are form values and route values in the request, form values take precedence.
Query string values are only used if there are no form values and no route values available as
parameters.
Model Extensibility
Two ways in which you can extend the MVC handling of MVC models are to create custom data
annotations and to create custom model binders.
The code example assumes that you have a model class in your MVC application called Car. It
also assumes that any request for a Car object includes values for color and brand in the form
collection.
Additional Reading: You can see more examples of custom model binders at the following
locations:
http://www.mgolchin.net/posts/20/dive-deep-into-mvc-imodelbinder-part-1
http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx
Question: You want to ensure that, when a user types a value into the Car Model Number
textbox when adding a new car to the website, the text entered is not already used by another
car in the database.
Would you use a custom validation data annotation or a custom model binder for this?
In MVC applications, you can place the data access code in the model along with the business
logic. Many software architects prefer to separate these two types of code because they serve
different purposes:
Business Logic. This code defines the objects that the web application manages, their
properties and their relationships with each other.
Data Access Logic. This code defines the operations necessary to persist data to a
database. This includes operations to create new records, read records, update records,
and delete records in database tables. A single object in the business logic layer may take
data from multiple database tables. This abstraction is handled by the data access logic.
MVC does not require you to separate business and data access logic and you can create MVC
model classes that implement both layers. This is often done in small or simple web applications
with small development teams. In these scenarios, Entity Framework classes are used directly in
the model classes.
In more complex situations, you need to place the business logic in MVC model classes and place
the data access logic in dedicated classes called repositories. When you take this approach,
model classes are independent of the database structure and do not include code that depends
on database table names, column names, or view names. This approach makes it easier to
redesign the database or move to a different data store or data access technology, without the
need to recode your entire application. Using this approach, you employ the Entity Framework in
your repository classes, but not in your model classes.
The CommentsController class uses the repository class instead of calling Entity Framework
methods
Note: By using the ICommentRepository interface, the code makes it easy to replace
CommentRespository with another implementation if you need to. However, the
CommentController code still creates a CommentRespository object. You have to modify the
object to make the replacement.
In an even better architecture you can replace CommentRepository with a different
implementation of ICommentRepository without any changes to the CommentController
class. This is an extremely flexible and adaptable approach and is called a loosely coupled
architecture
Question: You are building a site that collects information from customers for their accounts. You
want to ensure that customers enter a valid email address in the Email property. How would you
do this?
Question: You have been asked to create an intranet site that publishes a customer database,
created by the sales department, to all employees within your company. How would you create
the model with Entity Framework?