MVC Architecture
MVC Architecture
MVC Architecture
NET MVC 5
MVC Architecture
In this section, you will get an overview of MVC architecture. The MVC
architectural pattern has existed for a long time in software engineering. All
most all the languages use MVC with slight variation, but conceptually it
remains the same.
MVC stands for Model, View and Controller. MVC separates application into
three components - Model, View and Controller.
Model: Model represents shape of the data and business logic. It maintains
the data of the application. Model objects retrieve and store model state in a
database.
View: View is a user interface. View display data using model to the user and
also enables them to modify the data.
Controller: Controller handles the user request. Typically, user interact with
View, which in-turn raises appropriate URL request, this request will be
handled by a controller. The controller renders the appropriate view with the
model data as a response.
The following figure illustrates the interaction between Model, View and
Controller.
1
MVC Architecture
The following figure illustrates the flow of the user's request in ASP.NET MVC.
As per the above figure, when the user enters a URL in the browser, it goes
to the server and calls appropriate controller. Then, the Controller uses the
appropriate View and Model and creates the response and sends it back to the
user
2
Setup Development Environment
You can develop ASP.NET MVC application with appropriate version of Visual
Studio and .NET framework, as you have seen in the previous section of
version history.
Here, we will use MVC v5.2, Visual Studio 2017 Community edition and .NET
framework 4.6 to create our first MVC application.
From the New Project dialog as shown below, expand Visual C# node and
select Webin the left pane, and then select ASP.NET Web Application (.NET
Framework) in the middle pane. Enter the name of your
project MyMVCApplication . (You can give any appropriate name for your
application). Also, you can change the location of the MVC application by
clicking on Browse.. button. Finally, click OK.
3
Create MVC Project in Visual Studio
From the New ASP.NET Web Application dialog, select MVC (if not selected
already) as shown below.
4
Create MVC Application
5
Select Authenctication Type
Here, we are keeping the default authentication for our application which is
No Authentication. Click OK to continue.
Wait for some time till Visual Studio creates a simple MVC project using default
template as shown below.
6
First MVC Application
Now, press F5 to run the project in debug mode or Ctrl + F5 to run the project
without debugging. It will open home page in the browser as shown below.
7
MVC 5 project includes JavaScript and CSS files of bootstrap 3.0 by default.
So you can create responsive web pages. This responsive UI will change its
look and feel based on the screen size of the different devices. For example,
top menu bar will be changed in the mobile devices as shown below.
8
9
ASP.NET MVC Folder Structure
We have created our first MVC 5 application in the previous section. Visual
Studio creates the following folder structure for MVC application by default.
10
MVC Folder Structure
App_Data
App_Data folder can contain application data files like LocalDB, .mdf files, xml
files and other data related files. IIS will never serve files from App_Data
folder.
App_Start
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. MVC 5 includes
BundleConfig.cs, FilterConfig.cs and RouteConfig.cs by default. We will see
significance of these files later.
11
App_Start Folder
Content
Content folder contains static files like css files, images and icons files. MVC 5
application includes bootstrap.css, bootstrap.min.css and Site.css by default.
Content Folder
12
Controllers
Controllers folder contains class files for the controllers. Controllers handles
users' request and returns a response. MVC requires the name of all controller
files to end with "Controller". You will learn about the controller in the next
section.
Controller Folder
fonts
Fonts folder contains custom font files for your application.
13
Fonts folder
Models
Models folder contains model class files. Typically model class includes public
properties, which will be used by application to hold and manipulate
application data.
Scripts
Scripts folder contains JavaScript or VBScript files for the application. MVC 5
includes javascript files for bootstrap, jquery 1.10 and modernizer by default.
14
Scripts Folder
Views
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.
15
View Folder
Global.asax
Global.asax 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
Packages.config file is managed by NuGet to keep track of what packages and
versions you have installed in the application.
Web.config
Web.config file contains application level configurations.
16
Routing in MVC
In the ASP.NET Web Forms application, every URL must match with a specific
.aspx file. For example, a URL http://domain/studentsinfo.aspx must match
with the file studentsinfo.aspx that contains code and markup for rendering a
response to the browser.
Route
Route defines the URL pattern and handler information. All the configured
routes of an application stored in RouteTable and will be used by Routing
engine to determine appropriate handler class or file for an incoming request.
17
Configure a Route
Every MVC application must configure (register) at least one route, which is
configured by MVC framework by default. You can register a route
in RouteConfig class, which is in RouteConfig.cs under App_Start folder.
The following figure illustrates how to configure a Route in the RouteConfig
class .
18
As you can see in the above figure, the route is configured using the
MapRoute() extension method of RouteCollection, where name is "Default",
url pattern is "{controller}/{action}/{id}" and defaults parameter for
controller, action method and id parameter. Defaults specifies which
controller, action method or value of id parameter should be used if they do
not exist in the incoming request URL.
The same way, you can configure other routes using MapRoute method of
RouteCollection. This RouteCollection is actually a property
of RouteTable class.
URL Pattern
The URL pattern is considered only after domain name part in the URL. For
example, the URL pattern "{controller}/{action}/{id}" would look like
localhost:1234/{controller}/{action}/{id}. Anything after "localhost:1234/"
would be considered as controller name. The same way, anything after
controller name would be considered as action name and then value of id
parameter.
Routing in MVC
If the URL doesn't contain anything after domain name then the default
controller and action method will handle the request. For example,
http://lcoalhost:1234 would be handled by HomeController and Index method
as configured in the defaults parameter.
The following table shows which Controller, Action method and Id parameter
would handle different URLs considering above default route.
19
URL Controller Action Id
Multiple Routes
You can also configure a custom route using MapRoute extension method. You
need to provide at least two parameters in MapRoute, route name and url
pattern. The Defaults parameter is optional.
You can register multiple custom routes with different names. Consider the
following example where we register "Student" route.
routes.MapRoute(
name: "Student",
url: "students/{id}",
defaults: new { controller = "Student", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
}
As shown in the above code, URL pattern for the Student route
is students/{id}, which specifies that any URL that starts with
domainName/students, must be handled by StudentController. Notice that we
haven't specified {action} in the URL pattern because we want every URL that
starts with student should always use Index action of StudentController. We
have specified default controller and action to handle any URL request which
starts from domainname/students.
20
starts with /students then only it will consider second route which is default
route.
The following table shows how different URLs will be mapped to Student route:
Route Constraints
You can also apply restrictions on the value of parameter by configuring route
constraints. For example, the following route applies a restriction on id
parameter that the value of an id must be numeric.
Register Routes
Now, after configuring all the routes in RouteConfig class, you need to register
it in the Application_Start() event in the Global.asax. So that it includes all
your routes into RouteTable.
21
Register Route
Controller
In this section, you will learn about the Controller in ASP.NET MVC.
In ASP.NET MVC, every controller class name must end with a word
"Controller". For example, controller for home page must be HomeController
and controller for student must be StudentController. Also, every controller
class must be located in Controller folder of MVC folder structure.
22
Adding a New Controller
Now, let's add a new empty controller in our MVC application in Visual Studio.
In the previous section we learned how to create our first MVC application,
which in turn created a default HomeController. Here, we will create a new
StudentController.
In the Visual Studio, right click on the Controller folder -> select Add -> click
on Controller..
Note:
Scaffolding is an automatic code generation framework for ASP.NET web
applications. Scaffolding reduces the time taken to develop a controller,
view etc. in MVC framework. You can develop a customized scaffolding template
using T4 templates as per your architecture and coding standard.
23
Adding Controller
Adding Controller
In the Add Controller dialog, enter the name of the controller. Remember,
controller name must end with Controller. Let's enter StudentController and
click Add.
24
Adding Controller
Example: Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
}
}
As you can see above, the StudentController class is derived from Controller
class. Every controller in MVC must derived from this abstract Controller class.
This base Controller class contains helper methods that can be used for
various purposes.
Now, we will return a dummy string from Index action method of above
StudentController. Changing the return type of Index method from
ActionResult to string and returning dummy string is shown below. You will
learn about ActionResult in the next section.
Example: Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
25
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
// GET: Student
public string Index()
{
return "This is Index action method of StudentController";
}
}
}
We have already seen in the routing section that the URL
request http://localhost/student or http://localhost/student/index is handled
by the Index() method of StudentController class, shown above. So let's
invoke it from the browser and you will see the following page in the browser.
Action method
In this section, you will learn about the action method of controller class.
All the public methods of a Controller class are called Action methods. They
are like any other normal methods with the following restrictions:
26
Action Method
As you can see in the above figure, Index method is a public method and it
returns ActionResult using the View() method. The View() method is defined
in the Controller base class, which returns the appropriate ActionResult.
Default Route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{name}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
However, you can change the default action name as per your requirement in
RouteConfig class.
ActionResult
MVC framework includes various result classes, which can be return from an
action methods. There result classes represent different types of responses
such as html, file, string, json, javascript etc. The following table lists all the
result classes available in ASP.NET MVC.
27
Result Class Description
The ActionResult class is a base class of all the above result classes, so it can
be return type of action methods which returns any type of result listed above.
However, you can specify appropriate result class as a return type of action
method.
28
Result Class Description Base Controller Method
As you can see in the above table, View method returns ViewResult, Content
method returns string, File method returns content of a file and so on. Use
different methods mentioned in the above table, to return different types of
results from an action method.
return RedirectToAction("Index");
}
[HttpDelete]
public ActionResult Delete(int id)
{
// delete student from the database whose id matches with specified id
return RedirectToAction("Index");
}
Please note that action method paramter can be Nullable Type.
By default, the values for action method parameters are retrieved from the
request's data collection. The data collection includes name/values pairs for
form data or query string values or cookie values. Model binding in ASP.NET
MVC automatically maps the URL query string or form data collection to the
action method parameters if both names are matching.
29
Action Selectors
Action selector is the attribute that can be applied to the action methods. It
helps routing engine to select the correct action method to handle a particular
request. MVC 5 includes the following action selector attributes:
1. ActionName
2. NonAction
3. ActionVerbs
ActionName
ActionName attribute allows us to specify a different action name than the
method name. Consider the following example.
Example: ActionName
public class StudentController : Controller
{
public StudentController()
{
[ActionName("find")]
public ActionResult GetById(int id)
{
// get student from the database
return View();
}
}
In the above example, we have applied ActioName("find") attribute to
GetById action method. So now, action name is "find" instead of "GetById".
This action method will be invoked on http://localhost/student/find/1 request
instead of http://localhost/student/getbyid/1 request.
NonAction
NonAction selector attribute indicates that a public method of a Controller is
not an action method. Use NonAction attribute when you want public method
in a controller but do not want to treat it as an action method.
For example, the GetStudent() public method cannot be invoked in the same
way as action method in the following example.
30
Example: NonAction
public class StudentController : Controller
{
public StudentController()
{
[NonAction]
public Student GetStudnet(int id)
{
return studentList.Where(s => s.StudentId == id).FirstOrDefault();
}
}
ActionVerbs
In this section, you will learn about the ActionVerbs selectors attribute.
The ActionVerbs selector is used when you want to control the selection of an
action method based on a Http request method. For example, you can define
two different action methods with the same name but one action method
responds to an HTTP Get request and another action method responds to an
HTTP Post request.
The following figure illustrates the HttpGET and HttpPOST action verbs.
31
ActionVerbs
Http
method Usage
GET To retrieve the information from the server. Parameters will be appended in the query string.
HEAD Identical to GET except that server do not return message body.
OPTIONS OPTIONS method represents a request for information about the communication options supported by web
server.
Example: ActionVerbs
public class StudentController : Controller
{
public ActionResult Index()
{
return View();
32
}
[HttpPost]
public ActionResult PostAction()
{
return View("Index");
}
[HttpPut]
public ActionResult PutAction()
{
return View("Index");
}
[HttpDelete]
public ActionResult DeleteAction()
{
return View("Index");
}
[HttpHead]
public ActionResult HeadAction()
{
return View("Index");
}
[HttpOptions]
public ActionResult OptionsAction()
{
return View("Index");
}
[HttpPatch]
public ActionResult PatchAction()
{
return View("Index");
}
}
You can also apply multiple http verbs using AcceptVerbs attribute.
GetAndPostAction method supports both, GET and POST ActionVerbs in the
following example:
Example: AcceptVerbs
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get)]
public ActionResult GetAndPostAction()
{
return RedirectToAction("Index");
}
33
Model in ASP.NET MVC
In this section, you will learn about the Model in ASP.NET MVC framework.
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 like a database.
Model class holds data in public properties. All the Model classes reside in the
Model folder in MVC folder structure.
Adding a Model
Open our first MVC project created in previous step in the Visual Studio. Right
click on Model folder -> Add -> click on Class..
In the Add New Item dialog box, enter class name 'Student' and click Add.
This will add new Student class in model folder. Now, add Id, Name, Age
properties as shown below.
34
Example: Model class
namespace MVC_BasicTutorials.Models
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
}
So in this way, you can create a model class which you can use in View. You
will learn how to implement validations using model later.
View is a user interface. View displays data from the model to the user and
also enables them to modify the data.
35
View folders for Controllers
Note:
Shared folder contains views, layouts or partial views which will be shared among
multiple views.
.vbhtml Visual Basic Razor view. Supports Visual Basic with html tags.
36
View file extension Description
Create a View
In the Add View dialogue box, keep the view name as Index. It's good practice
to keep the view name the same as the action method name so that you don't
have to specify view name explicitly in the action method while returning the
view.
37
View
Now, select Student from the Model class dropdrown. Model class dropdown
automatically displays the name of all the classes in the Model folder. We have
already created Student Model class in the previous section, so it would be
included in the dropdown.
View
38
Check "Use a layout page" checkbox and select _Layout.cshtml page for this
view and then click Add button. We will see later what is layout page but for
now think it like a master page in MVC.
This will create Index view under View -> Student folder as shown below:
View
Views\Student\Index.cshtml:
@model IEnumerable<MVC_BasicTutorials.Models.Student>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
39
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
</table>
As you can see in the above Index view, it contains both Html and razor codes.
Inline razor expression starts with @ symbol. @Html is a helper class to
generate html controls. You will learn razor syntax and html helpers in the
coming sections.
40
Index.cshtml
41
Index View
Note:
Every view in the ASP.NET MVC is derived from WebViewPage class included in
System.Web.Mvc namespace.
The following code snippet shows StudentController and Student model class
& view created in the previous sections.
Example: StudentController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
42
using System.Web.Mvc;
using MVC_BasicTutorials.Models;
namespace MVC_BasicTutorials.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
return View();
}
}
}
Example: Student Model class
namespace MVC_BasicTutorials.Models
{
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
}
Example: Index.cshtml to display student list
@model IEnumerable<MVC_BasicTutorials.Models.Student>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StudentName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th></th>
</tr>
43
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
@Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.StudentId })
</td>
</tr>
}
</table>
Now, to run it successfully, we need to pass a model object from controller to
Index view. As you can see in the above Index.cshtml, it uses IEnumerable of
Student as a model object. So we need to pass IEnumerable of Student model
from the Index action method of StudentController class as shown below.
return View(studentList);
}
}
As you can see in the above code, we have created a List of student objects
for an example purpose (in real life applicatoin, you can fetch it from the
database). We then pass this list object as a parameter in the View() method.
The View() method is defined in base Controller class, which automatically
binds model object to the view.
44
Now, you can run the MVC project by pressing F5 and navigate
to http://localhost/Student. You will see following view in the browser.
Model Binding
In this section, you will learn about model binding in MVC framework.
To understand the model binding in MVC, first let's see how you can get the
http request values in the action method using traditional ASP.NET style. The
following figure shows how you can get the values from HttpGET and HttpPOST
request by using the Request object directly in the action method.
45
Accessing Request
Data
As you can see in the above figure, we use the Request.QueryString and
Request (Request.Form) object to get the value from HttpGet and HttpPOST
request. Accessing request values using the Request object is a cumbersome
and time wasting activity.
With model binding, MVC framework converts the http request values (from
query string or form collection) to action method parameters. These
parameters can be of primitive type or complex type.
46
Model
Binding
You can also have multiple parameters in the action method with different
data types. Query string values will be converted into paramters based on
matching name.
return View();
}
47
[Display(Name="Name")]
public string StudentName { get; set; }
public int Age { get; set; }
public Standard standard { get; set; }
}
return RedirectToAction("Index");
}
So now, MVC framework will automatically maps Form collection values to
Student type parameter when the form submits http POST request to Edit
action method as shown below.
Model Binding
48
FormCollection
You can also include FormCollection type parameter in the action method
instead of complex type, to retrieve all the values from view form fields as
shown below.
Model Binding
Bind Attribute
ASP.NET MVC framework also enables you to specify which properties of a
model class you want to bind. The [Bind] attribute will let you specify the
exact properties a model binder should include or exclude in binding.
In the following example, Edit action method will only bind StudentId and
StudentName property of a Student model.
return RedirectToAction("Index");
}
You can also use Exclude properties as below.
return RedirectToAction("Index");
}
49
The Bind attribute will improve the performance by only bind properties which
you needed.
Value providers are responsible for collecting values from request and Model
Binders are responsible for populating values.
Model
Binding in MVC
Default value provider collection evaluates values from the following sources:
50