Banking and Financial Services - Capital Markets Technology Excellence Group Nishikant Kotgire

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

ASP.

NET MVC
08/04/2010

Banking and Financial Services – Capital Markets


Technology Excellence Group

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.

Terms used in this document


Term Description
AJAX Asynchronous Javascript and XML

HTML Hypertext Markup Language

HTTP Hyper Text Transfer Protocol

IDE Integrated Development Environment

MVC Model-View-Controller

REST Representational State Transfer

SEO Search Engine Optimization

TDD Test Driven Development

URL Uniform Resource Locator

UI User Interface

VS / VS.NET Visual Studio .NET, an IDE from Microsoft for developing .NET and
Silverlight applications

XML Extensible Markup Language

About the Author


Nishikant Kotgire is part of the BFS3 Technology Excellence Group. Nishikant is currently
working on the BI portals project using Silverlight 3.

TCS Public
Table of Contents

ABOUT THIS DOCUMENT ........................................................................................................ 2


INTENDED AUDIENCE.................................................................................................................................................2
TERMS USED IN THIS DOCUMENT ..............................................................................................................................2
ABOUT THE AUTHOR............................................................................................................... 2
INTRODUCTION ....................................................................................................................... 4
MOTIVATING MVC ....................................................................................................................................................5
COMPARING THE MVC FRAMEWORK TO CLASSIC ASP.NET ................................................. 6
A URL DOES NOT EQUAL A PAGE ...........................................................................................................................6
REPRESENTATIONAL STATE TRANSFER (REST)........................................................................................................7
CODE BEHIND V/S CONTROLLERS ............................................................................................................................8
RESOURCES .............................................................................................................................................................. 10
LIFECYCLE ................................................................................................................................................................ 10
UNDERSTANDING MODELS, VIEWS, AND CONTROLLERS .................................................. 11
CREATING A NEW ASP.NET MVC APPLICATION ................................................................................................ 11
UNDERSTANDING THE FOLDER STRUCTURE OF A PROJECT................................................................................. 12
UNDERSTANDING ASP.NET ROUTING ................................................................................................................. 12
UNDERSTANDING CONTROLLERS .......................................................................................................................... 14
UNDERSTANDING VIEWS ........................................................................................................................................ 15
UNDERSTANDING MODELS .................................................................................................................................... 15
REFERENCES........................................................................................................................... 17
APPENDIX............................................................................................................................... 17

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

Figure: Model-View-Controller (MVC)

• 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.

A URL Does Not Equal a Page


When you build a traditional ASP.NET Web Forms application or an Active Server
Pages application, there is a one-to-one correspondence between a URL and a page. If you
request a page named SomePage.aspx from the server, then there had better be a page on
disk named SomePage.aspx. If the SomePage.aspx file does not exist, you get an ugly 404 –
Page Not Found error.
When building an ASP.NET MVC application, in contrast, there is no correspondence
between the URL that you type into your browser’s address bar and the files that you find in
your application. In an ASP.NET MVC application, a URL corresponds to a controller action
instead of a page on disk.
In a traditional ASP.NET or ASP application, browser requests are mapped to pages. In
an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions.
An ASP.NET Web Forms application is content-centric. An ASP.NET MVC application, in
contrast, is application logic centric.

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.

Figure: Contrasting 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,

Sample ASP.NET Web Forms Page


public class CustomerPage : Page
{
protected withevents TextBox FirstName;
protected withevents TextBox LastName;
protected withevents GridView OrdersGrid;
protected override void OnLoad(EventArgs e)
{
UserInformation info = (UserInformation)Session["User"];
this.FirstName.Text = info.FirstName;
this.LastName.Text = info.LastName;
var dal = new OrdersDAL();
this.OrdersGrid.DataSource = dal.GetOrders(info.ID);
this.OrdersGrid.DataBind();
}

protected void OrdersGrid_RowDataBound(object sender,


GridViewRowEventArgs e)
{
if (e.Row.ItemType == DataRowControlState.DataItem)
{
e.Row.Cells[3].Text = Order)e.Row.DataItem).HasShipped ? "Yes"
: "No";
}
}
}

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.

Sample ASP.NET MVC Controller


public class CustomerModel
{
public UserInformation User { get; set; }
public IEnumerable<Order> Orders { get; set; }

TCS Public
}

public class CustomerController : Controller


{
public ActionResult Index()
{
var dal = new OrdersDAL();
var user = (UserInformation)Session["User"];
return View(new CustomerModel
{
User = user,
Orders = dal.GetOrders(user.ID)
});
}
}

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

Creating a New ASP.NET MVC Application


The ASP.NET MVC Framework includes Visual Studio Project Templates that make it
easy to create a new web application with it. Simply select the File->New Project menu item
and choose the "ASP.NET MVC Web Application" template to create a new web application
using it.
By default when you create a new application using this option, Visual Studio will
create a new solution for you and add two projects into it. The first project is a web project
where you'll implement your application. The second is a testing project that you can use to
write unit tests against it:

Figure: Folder structure of an ASP.NET MVC application

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.

Understanding ASP.NET Routing


A browser request gets mapped to a controller action through a feature of the
ASP.NET framework called ASP.NET Routing. ASP.NET Routing is used by the ASP.NET MVC
framework to route incoming requests to controller actions. ASP.NET Routing uses a route
table to handle incoming requests. This route table is created when your web application first
starts. The route table is setup in the Global.asax file. The default MVC Global.asax file is shown
below,

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

public class MvcApplication : System.Web.HttpApplication


{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}",
// URL with parameters

TCS Public
new { controller = "Home", action = "Index", id = "" }
// Parameter defaults
);

protected void Application_Start()


{
RegisterRoutes(RouteTable.Routes);
}
}
}

When an ASP.NET application first starts, the Application_Start() method is called. In


the above code, this method calls the RegisterRoutes() method and the RegisterRoutes()
method creates the default route table.
The default route table consists of one route. This default route breaks all incoming
requests into three segments (a URL segment is anything between forward slashes). The first
segment is mapped to a controller name, the second segment is mapped to an action name,
and the final segment is mapped to a parameter passed to the action named Id.
For example, consider the following URL:
/Product/Details/3
This URL is parsed into three parameters like this:
Controller = Product
Action = Details
Id = 3
The Default route defined in the Global.asax file includes default values for all three
parameters. The default Controller is Home, the default Action is Index, and the default Id is an
empty string. With these defaults in mind, consider how the following URL is parsed:
/Employee
This URL is parsed into three parameters like this:
Controller = Employee
Action = Index
Id = “”
Finally, if you open an ASP.NET MVC Application without supplying any URL (for example,
http://localhost) then the URL is parsed like this:
Controller = Home
Action = Index
Id = “”
The request is routed to the Index() action on the HomeController class.

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();
}

public ActionResult About()


{
ViewData["Title"] = "About Page";

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" %>

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent"


runat="server">
<h2>About</h2>
<p>
Put content here.
</p>
</asp:Content>

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

You might also like