Banking and Financial Services - Capital Markets Technology Excellence Group Nishikant Kotgire
Banking and Financial Services - Capital Markets Technology Excellence Group Nishikant Kotgire
Banking and Financial Services - Capital Markets Technology Excellence Group Nishikant Kotgire
NET MVC
08/04/2010
NISHIKANT KOTGIRE
[email protected]
TCS Public
About this document
This document gives introduction to Microsoft’s ASP.NET MVC Framework.
Intended Audience
This document is targeted at developers working on ASP.NET.
MVC Model-View-Controller
UI User Interface
VS / VS.NET Visual Studio .NET, an IDE from Microsoft for developing .NET and
Silverlight applications
TCS Public
Table of Contents
TCS Public
Introduction
MVC stands for Model-View-Controller and is one of the most popular design patterns
for decoupling data access and business logic from data presentation and user interaction.
The ASP.NET MVC Framework addresses aspects of programming that are extremely
important for developers and their productivity such as code reusability, testing, and
separation of presentation and business logic concerns.
An MVC Application is designed and implemented using the following three attributes
• Model: The model contains the core information for an application. This includes the
data and validation rules as well as data access and aggregation logic.
• View: The view encapsulates the presentation of the application, and in ASP.NET this is
typically the HTML markup.
• Controller: The controller contains the control-flow logic. It interacts with the Model
and Views to control the flow of information and execution of the application.
TCS Public
This separation of entity allows you to have nimbleness and flexibility in building and
maintaining your application. For example, by separating the views, you can iterate on the
appearance of your application without touching on any of the core business logic. You can
also separate work by role, so that, for example designers can work on the views, while
developers work on the model.
ASP.NET MVC brings the power of this development paradigm to ASP.NET development,
allowing you to use your .NET development skills to build MVC applications. It gives you
• Complete control over your HTML Markup
• Enables rich AJAX and jQuery integration
• Allows you to create SEO-friendly URLs for your site
• Makes Test Driven Development (TDD) easy
Motivating MVC
Most applications, and especially Web applications, have their presentation layer
mixed up with some business logic and data access code. As an example, think of a classic
ASP.NET page. You define the user interface by composing and configuring server controls
until you obtain the desired markup. Next, you use a code-behind class to add some handlers
for the various events fired by controls and provide any required glue code. In such pages,
more often than not, data access code is interspersed with presentation logic. Such ASP.NET
pages whose code-behind classes contain a mixture of presentation, business and data access
code, are quite difficult to maintain. And they are definitely challenging to test appropriately.
User interface facilities (i.e., wizards and tools in Visual Studio) tend to encourage
developers to put in the presentation layer more than it should. The presentation layer acts as
a catch-all for logic that reasonably belongs to other layers. At the end of the day, you can still
have the application working and perform well. Behind the scene, though, you get a too high
level of coupling and subsequently high costs of maintenance. What if, in fact, at some point
you need to add a new feature or re-implement an existing one? Not having a well designed
structure of classes and lacking a clean separation of presentation, business and data layers,
most that you can do is cutting and pasting code and run pages over and over again to test
results against expectations.
The classic code-behind model of ASP.NET provides the tools for building great and
well-designed applications, but it leaves most of it up to the individual developer or team. As a
result, too many applications out there work well, but are not well designed. Over the years,
this fact raised the need of a radically different approach to Web programming. The MVC
pattern was soon identified as an excellent approach to Web development. MVC ensures a
clean separation between the data model and the user interface in such a way that changes to
the user interface doesn’t affect data handling. At the same time, the data model and related
access code can be refactored without the need of changing the user interface accordingly.
TCS Public
Comparing the MVC Framework to Classic ASP.NET
The ASP.NET MVC Framework is essentially the Microsoft's attempt to create an
ASP.NET programming environment centered on the MVC pattern. For the time being, the
MVC Framework should be considered an alternative to Web Forms. To some extent, the MVC
Framework and Web Forms have in common more or less what cars and motorcycles share.
Both can take you somewhere else, but with different speed, comfort, sense of freedom, size
of the trunk.
The MVC Framework doesn't support classic postbacks and viewstate and doesn't
consider any URL as the endpoint to a physical server file to parse and compile to a class. In
ASP.NET, you have a 1:1 correspondence between a URL and a resource.
In the MVC Framework, a URL is seen as the mean to address a logical server resource,
but not necessarily an ASPX file to parse. So the URLs employed by the pages of an MVC
Framework application have a custom format that the application itself mandates. In the end,
the MVC Framework employs a centralized HTTP handler that recognizes an application-
specific syntax for links. In addition, each addressable resource exposes a well-known set of
operations and a uniform interface for executing operations.
TCS Public
Representational State Transfer (REST)
Have you ever heard about Representational State Transfer, or REST for short? Well,
REST is an architectural pattern that defines how network resources should be defined and
addressed in order to gain shorter response times, clear separation of concerns between the
front-end and back-end of a networked system. REST is based on three following principles:
• An application expresses its state and implements its functionality by acting on logical
resources.
• Each resource is addressed using a specific URL syntax.
• All addressable resources feature a contracted set of operations
As you can see, the MVC Framework fulfills it entirely. So here's an alternate way of looking
at the MVC Framework. It is an ASP.NET framework that performs data exchange by using a
REST model versus the postback model of classic ASP.NET. Each page is split into two distinct
components -controller and view - that operate over the same model of data. This is opposed
to the classic code-behind model where no barrier is set that forces you to think in terms of
separation of concerns and controllers and views. However, by keeping the code-behind class
as thin as possible, and designing the business layer appropriately, a good developer could
achieve separation of concerns even without adopting MVC and its overhead. MVC, however,
is a model superior to a properly-done code-behind for its inherent support for test-driven
development (TDD).
The figure below summarizes classic ASP.NET and the MVC Framework.
REST is a possible alternative to the postback model, whereas MVC is an alternative to code-
behind.
TCS Public
Code Behind v/s Controllers
ASP.NET MVC's version of the code-behind file is the controller class. The
controller class works differently however; with ASP.NET MVC, there aren't any server-side
controls, page lifecycle, and some of those other familiar page components that web forms
developers are used to. Take a look at a sample code-behind page,
Here we have a page that pulls the first and last name from a session variable that
stores a UserInformation object across page requests. Next, the code-behind invokes a
method in the data access layer to get orders for a specific user by its ID, and binds them to
the grid. So, in this simple example, the code-behind file is responsible for assigning values to
the individual controls in the page, for loading data into a grid, and for communicating with
the data access layer. With MVC, we see the alternative controller approach.
TCS Public
}
There are some quite substantial changes between this MVC controller and the
previous ASP.NET web form. First, the CustomerModel class contains the actual data that gets
displayed in the view. In the web form, the code-behind file assigns the data to the view; in
MVC, this responsibility will be shown later. Additionally, the controller creates this model for
the view, as well as does the data access dirty work, and accessing the data from the session.
So how do we work with textboxes and grids and those other controls we have been
so used to working with? Below is a sample MVC view that displays the UI.
Sample View
<@Page .. >
<html>
<body>
<% Html.BeginForm(); %>
<div>
<span>First</span>
<%= Html.TextBox("FirstName", Model.User.FirstName) %>
</div>
<div>
<span>Last</span>
<%= Html.TextBox("LastName", Model.User.LastName) %>
</div>
<div>
<table>
<thead>
<tr>
<th>Date</th>
<th>Amount</th>
<th># Products</th>
<th>Has Shipped?</th>
</tr>
</thead>
<tbody>
<% foreach (var order in Model.Orders) { %>
<tr>
<td><%= order.Date %></td>
<td><%= order.Amount.ToString("C") %></td>
TCS Public
<td><%= order.ProductCount %></td>
<td><%= order.HasShipped ? "Yes" : "No" %></td>
</tr>
<% } %>
</tbody>
</table>
</div>
<% Html.EndForm(); %>
</body>
</html>
There are quite the changes than web forms developers are used to. The MVC view
takes over more of the ownership of displaying the data within the UI. It does look similarly to
the way web forms works, with the addition of the view specifying the data to load, and the
view taking over how the UI will appear without the involvement of a code-behind file.
Resources
In ASP.NET web forms, developers used a wide array of external resources to store data
with. Users could leverage mechanisms like Session, Cache, Application, and other collections
for storing data across page postbacks. ASP.NET MVC still uses these to retain its data, but this
has gotten better.
LifeCycle
With ASP.NET web forms, the page fires an Init, Load, PreRender, and Unload events
(to name a few). ASP.NET MVC, however, doesn't leverage this lifecycle; instead, it runs
requests to action methods (usually one, but other action methods can run additionally
through some helper methods).
TCS Public
Understanding Models, Views, and Controllers
TCS Public
Understanding the Folder Structure of a Project
The default directory structure of an ASP.NET MVC Application has 3 top-level
directories:
• /Controllers
• /Models
• /Views
As you can probably guess, it is recommend that you put your Controller classes
underneath the /Controllers directory, your data model classes underneath your /Models
directory, and your view templates underneath your /Views directory.
While the ASP.NET MVC framework doesn't force you to always use this structure, the
default project templates use this pattern and it is an easy way to structure your application.
Unless you have a good reason to use an alternative file layout.
Global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}",
// URL with parameters
TCS Public
new { controller = "Home", action = "Index", id = "" }
// Parameter defaults
);
TCS Public
Understanding Controllers
A controller is responsible for controlling the way that a user interacts with an MVC
application. A controller contains the flow control logic for an ASP.NET MVC application. A
controller determines what response to send back to a user when a user makes a browser
request.
A controller is just a class (for example, a Visual Basic or C# class). The sample ASP.NET
MVC application includes a controller named HomeController.cs located in the Controllers
folder. The content of the HomeController.cs file is listed below,
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
return View();
}
}
}
Notice that the HomeController has two methods named Index() and About(). These
two methods correspond to the two actions exposed by the controller. The URL /Home/Index
invokes the HomeController.Index() method and the URL /Home/About invokes the
HomeController.About() method.
Any public method in a controller is exposed as a controller action. You need to be
careful about this. This means that any public method contained in a controller can be
invoked by anyone with access to the Internet by entering the right URL into a browser.
TCS Public
Understanding Views
The two controller actions exposed by the HomeController class, Index() and About(),
both return a view. A view contains the HTML markup and content that is sent to the browser.
A view is the equivalent of a page when working with an ASP.NET MVC application.
You must create your views in the right location. The HomeController.Index() action
returns a view located at the following path:
\Views\Home\Index.aspx
The HomeController.About() action returns a view located at the following path:
\Views\Home\About.aspx
In general, if you want to return a view for a controller action, then you need to create
a subfolder in the Views folder with the same name as your controller. Within the subfolder,
you must create an .aspx file with the same name as the controller action.
About.aspx
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
If you ignore the first line in Listing 3, most of the rest of the view consists of standard
HTML. You can modify the contents of the view by entering any HTML that you want here.
A view is very similar to a page in Active Server Pages or ASP.NET Web Forms. A view
can contain HTML content and scripts. You can write the scripts in your favorite .NET
programming language (for example, C# or Visual Basic .NET). You use scripts to display
dynamic content such as database data.
Understanding Models
An MVC model contains all of your application logic that is not contained in a view or a
controller. The model should contain all of your application business logic, validation logic,
and database access logic.
A view should contain only logic related to generating the user interface. A controller
should only contain the bare minimum of logic required to return the right view or redirect
the user to another action (flow control). Everything else should be contained in the model.
TCS Public
In general, you should strive for fat models and skinny controllers. Your controller
methods should contain only a few lines of code. If a controller action gets too fat, then you
should consider moving the logic out to a new class in the Models folder.
TCS Public
References
1. http://www.asp.net/mvc/
2. http://www.asp.net/mvc/whatisaspmvc/
3. http://www.asp.net/learn/mvc/tutorial-02-cs.aspx
4. http://dotnetslackers.com/articles/aspnet/Introduction-to-ASP-NET-MVC-2-0.aspx
5. http://dotnetslackers.com/articles/aspnet/AnArchitecturalViewOfTheASPNETMVCFra
mework.aspx
6. http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx
7. http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-
1.aspx
Appendix
1. ASP.NET MVC is a free and fully supported framework for building web applications
that use the model-view-controller pattern.
2. ASP.NET MVC 2.0 is shipped as part of the ASP.NET 4.0 Framework, or as a separate
add-on for previous versions of ASP.NET.
3. For information on upgrading to ASP.NET MVC 2.0, see our How to Upgrade
instructions. For an overview of changes, see our What's New summary.
TCS Public