The MVC Programming Model
The MVC Programming Model
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.
The Model is the part of the application that handles the logic for the application data.
Often model objects retrieve data (and store data) from a database.
The View is the parts of the application that handles the display of the data.
Most often the views are created from the model data.
The Controller is the part of the application that handles user interaction.
Typically controllers read data from a view, control user input, and send input data to the
model.
The MVC separation helps you manage complex applications, because you can focus on one
aspect a time. For example, you can focus on the view without depending on the business
logic. It also makes it easier to test an application.
The MVC separation also simplifies group development. Different developers can work on
the view, the controller logic, and the business logic in parallel.
Web Forms vs MVC
The MVC programming model is a lighter alternative to traditional ASP.NET (Web Forms).
It is a lightweight, highly testable framework, integrated with all existing ASP.NET features,
such as Master Pages, Security, and Authentication.
Visual Studio Express is a development tool tailor made for MVC (and Web Forms).
If you install Visual Studio Express, you will get more benefits from this tutorial.
If you want to install Visual Studio Express, click on one of these links:
Visual Web Developer 2010 (If you have Windows Vista or XP)
What We Will Do
Visual Web Developer offers different templates for building web applications.
We will use Visual Web Developer to create an empty MVC Internet application with
HTML5 markup.
When the empty Internet application is created, we will gradually add code to the application
until it is fully finished. We will use C# as the programming language, and the newest Razor
server code markup.
Along the way we will explain the content, the code, and all the components of the
application.
We will explore the content of the files and folders in the next chapter of this tutorial.
MVC Folders
A typical ASP.NET MVC web application has the following folder content:
Application information
Properties
References
Application folders
App_Data Folder
Content Folder
Controllers Folder
Models Folder
Scripts Folder
Views Folder
Configuration files
Global.asax
packages.config
Web.config
The folder names are equal in all MVC applications. The MVC framework is based on
default naming. Controllers are in the Controllers folder, Views are in the Views folder, and
Models are in the Models folder. You don't have to use the folder names in your application
code.
Standard naming reduces the amount of code, and makes it easier for developers to
understand MVC projects.
We will add an SQL database to the App_Data folder, later in this tutorial.
Visual Web Developer automatically adds a themes folder to the Content folder. The themes
folder is filled with jQuery styles and pictures. In this project you can delete the themes
folder.
Visual Web Developer also adds a standard style sheet file to the project: the file Site.css in
the content folder. The style sheet file is the file to edit when you want to change the style of
the application.
We will edit the style sheet file (Site.css) file in the next chapter of this tutorial.
MVC requires the name of all controller files to end with "Controller".
Visual Web Developer has created a Home controller (for the Home and the About page) and
an Account controller (for Login pages):
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder
(inside the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout
pages).
We will edit the layout files in the next chapter of this tutorial.
By default Visual Web Developer fills this folder with standard MVC, Ajax, and jQuery files:
Note: The files named "modernizr" are JavaScript files used for supporting HTML5 and CSS3
features in the application.
ASP.NET MVC - Styles and Layout
To learn ASP.NET MVC, we are Building an Internet Application.
Adding a Layout
The file _Layout.cshtml represent the layout of each page in the application. It is located in
the Shared folder inside the Views folder.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"></script>
<script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")"></script>
</head>
<body>
<ul id="menu">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Movies", "Index", "Movies")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
<section id="main">
@RenderBody()
<p>Copyright W3schools 2012. All Rights Reserved.</p>
</section>
</body>
</html>
HTML Helpers
In the code above, HTML helpers are used to modify HTML output:
You will learn more about HTML helpers in a later chapter of this tutorial.
Razor Syntax
In the code above, the code marked red are C# using Razor markup.
You can learn about Razor markup for both C# and VB (Visual Basic) in our Razor tutorial.
Adding Styles
The style sheet for the application is called Site.css. It is located in the Content folder.
Open the file Site.css and swap the content with this:
body
{
font: "Trebuchet MS", Verdana, sans-serif;
background-color: #5c87b2;
color: #696969;
}
h1
{
border-bottom: 3px solid #cc9900;
font: Georgia, serif;
color: #996600;
}
#main
{
padding: 20px;
background-color: #ffffff;
border-radius: 0 4px 4px 4px;
}
a
{
color: #034af3;
}
/* Menu Styles ------------------------------*/
ul#menu
{
padding: 0px;
position: relative;
margin: 0;
}
ul#menu li
{
display: inline;
}
ul#menu li a
{
background-color: #e8eef4;
padding: 10px 20px;
text-decoration: none;
line-height: 2.8em;
/*CSS3 properties*/
border-radius: 4px 4px 0 0;
}
ul#menu li a:hover
{
background-color: #ffffff;
}
/* Forms Styles ------------------------------*/
fieldset
{
padding-left: 12px;
}
fieldset label
{
display: block;
padding: 4px;
}
input[type="text"], input[type="password"]
{
width: 300px;
}
input[type="submit"]
{
padding: 4px;
}
/* Data Styles ------------------------------*/
table.data
{
background-color:#ffffff;
border:1px solid #c3c3c3;
border-collapse:collapse;
width:100%;
}
table.data th
{
background-color:#e8eef4;
border:1px solid #c3c3c3;
padding:3px;
}
table.data td
{
border:1px solid #c3c3c3;
padding:3px;
}
The _ViewStart File
The _ViewStart file in the Shared folder (inside the Views folder) contains the following
content:
@{Layout = "~/Views/Shared/_Layout.cshtml";}
If you remove this file, you must add this line to all views.
You will learn more about views in a later chapter of this tutorial.
In our example, Visual Web Developer has created the following files: HomeController.cs
(for the Home and About pages) and AccountController.cs (For the Log On pages):
Web servers will normally map incoming URL requests directly to disk files on the server.
For example: a URL request like "http://www.w3schools.com/default.asp" will map directly
to the file "default.asp" at the root directory of the server.
The MVC framework maps differently. MVC maps URLs to methods. These methods are in
classes called "Controllers".
Controllers are responsible for processing incoming requests, handling input, saving data, and
sending a response to send back to the client.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{return View();}
Visual Web Developer has created an Account folder, a Home folder, and a Shared folder
(inside the Views folder).
The Account folder contains pages for registering and logging in to user accounts.
The Home folder is used for storing application pages like the home page and the about page.
The Shared folder is used to store views shared between controllers (master pages and layout
pages).
ASP.NET File Types
The following HTML file types can be found in the Views Folder:
ASP.NET Razor
.cshtml
C#
ASP.NET Razor
.vbhtml
VB
<h1>Welcome to W3Schools</h1>
<h1>About Us</h1>
Click on the "Home" tab and the "About" tab to see how it works.
Congratulations
Congratulations. You have created your first MVC Application.
Note: You cannot click on the "Movies" tab yet. We will add code for the "Movies" tab in the
next chapters of this tutorial.
The database needed for this tutorial can be created with these simple steps:
Visual Web Developer automatically creates the database in the App_Data folder.
Note: In this tutorial it is expected that you have some knowledge about SQL databases. If
you want to study this topic first, please visit our SQL Tutorial.
To create a new table in the database, right-click the Tables folder, and select Create Table.
Title nvarchar(100) No
Director nvarchar(100) No
Date datetime No
Columns explained:
Title is a 100 character text column to store the name of the movie.
After creating the columns described above, you must make the ID column the table's
primary key (record identifier). To do this, click on the column name (ID) and select
Primary Key. Also, in the Column Properties window, set the Identity property to True:
When you have finished creating the table columns, save the table and name it MovieDBs.
Note:
We have deliberately named the table "MovieDBs" (ending with s). In the next chapter, you
will see the name "MovieDB" used for the data model. It looks strange, but this is the naming
convention you have to use to make the controller connect to the database table.
Right-click the MovieDBs table in the Database Explorer window and select Show Table
Data.
Note: The ID column is updated automatically. You should not edit it.
MVC Models
The MVC Model contains all application logic (business logic, validation logic, and data
access logic), except pure view and controller logic.
Visual Web Developer automatically creates an AccountModels.cs file that contains the
models for application security.
In the Solution Explorer, right-click the Models folder, and select Add and Class.
Name the class MovieDB.cs, and click Add.
Edit the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcDemo.Models
{
public class MovieDB
{
public int ID { get; set; }
public string Title { get; set; }
public string Director { get; set; }
public DateTime Date { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<MovieDB> Movies { get; set; }
}
}
Note:
We have deliberately named the model class "MovieDB". In the previous chapter, you saw
the name "MovieDBs" (ending with s) used for the database table. It looks strange, but this is
the naming convention you have to use to make the model connect to the database table.
Re-Build your project: Select Debug, and then Build MvcDemo from the menu.
In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
Set controller name to MoviesController
Select template: Controller with read/write actions and views, using Entity Framework
Select model class: MovieDB (MvcDemo.Models)
Select data context class: MovieDBContext (MvcDemo.Models)
Select views Razor (CSHTML)
Click Add
Create.cshtml
Delete.cshtml
Details.cshtml
Edit.cshtml
Index.cshtml
Adding a Connection String
Add the following element to the <connectionStrings> element in your Web.config file:
<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|\Movies.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
Visual Web Developer automatically creates an AccountModels.cs file that contains the
models for application authentication.
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.",
MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not
match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
}
The Register Model
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength
= 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
HTML Helpers
With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.
Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But
HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not
have an event model and a view state.
HTML Links
The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.
With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller
action.
Razor Syntax:
ASP Syntax:
The first parameter is the link text, and the second parameter is the name of the controller
action.
Property Description
Note: You can pass values to a controller action. For example, you can pass the id of a
database record to a database edit action:
BeginForm()
EndForm()
TextArea()
TextBox()
CheckBox()
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.")
%>
<% using (Html.BeginForm()){%>
<p>
<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<label for="Password">Confirm Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>
</p>
<p>
<label for="Profile">Profile:</label>
<%= Html.TextArea("Profile", new {cols=60, rows=10})%>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>
<%}%>
This function copies all your application files, controllers, models, images, and all the
required DLL files for MVC, Web Pages, Razor, Helpers, and SQL Server Compact (if a
database is used).
Sometimes you don't want to use this option. Maybe your hosting provider only supports
FTP? Maybe you already have a web site based on classic ASP? Maybe you want to copy the
files yourself? Maybe you want to use Front Page, Expression Web, or some other publishing
software?
Will you get a problem? Yes, you will. But you can solve it.
To perform a web copy, you have to know how to include the right files, what DDL files to
copy, and where store them.
Follow these steps:
If your App_Data folder contains test data, don't copy the App_Data folder (see SQL Data
below).
Example C#
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add invariant="System.Data.SqlServerCe.4.0"
name="Microsoft SQL Server Compact 4.0"
description=".NET Framework Data Provider for Microsoft SQL Server Compact"
type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe,
Version=4.0.0.1,Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
</configuration>
If you have to copy the SQL data files (.sdf files), you should delete everything in the
database, and then copy the empty .sdf file from your development computer to the server.
Classes
Class Description
Interfaces
Interface Description
IAuthorizationFilter Defines the methods that are required for an authorization filter.
IControllerFactory Defines the methods that are required for a controller factory.
IExceptionFilter Defines the methods that are required for an exception filter.
IModelBinder Defines the methods that are required for a model binder.
IMvcFilter Defines members that specify the order of filters and whether multiple
filters are allowed.
IResultFilter Defines the methods that are required for a result filter.
Defines the contract for temporary-data providers that store data that is
ITempDataProvider
viewed on the next request.
Defines the methods that are required for a value provider in ASP.NET
IValueProvider
MVC.
IViewDataContainer Defines the methods that are required for a view data dictionary.
IViewEngine Defines the methods that are required for a view engine.
Defines the methods that are required in order to cache view locations
IViewLocationCache
in memory.