under the property pages, as shown in Figure 20-44.
The tools included in IIS enable you to manage all the settings you saw earlier, including the
creation and management of users, roles, application settings, and SMTP settings. You are also
given access to more powerful administration tools that enable you to configure advanced settings
such as the .NET compilation behavior, .NET trust level, and session state configuration. These
tools enable you to maintain a web application running on any IIS server without needing to resort
to editing the Web.config
configuration file.
fiGure 20-44
suMMary
In this chapter you learned how to create ASP.NET applications using the Web Site and Web
Application projects. The improvements to the HTML Designer and the new CSS tools in Visual
Studio 2010 provide you with great power over the layout and visual design of web pages. The vast
summary .
435
number of web controls included in ASP.NET enables you to quickly put together highly functional
web pages. Through the judicious use of JavaScript, ASP.NET AJAX, and control extenders in the
AJAX Control Toolkit, you can provide a very rich user experience in your web applications.
Of course, there’s much more to web development than we covered here. Chapters 21 and 22
continue the discussion on building rich web applications by exploring the latest web technologies
from Microsoft: ASP.NET MVC and Silverlight. Chapter 42 provides detailed information about
the tools and techniques available for effective debugging of web applications. Finally, Chapter 49
walks you through the deployment options for web applications. If you are looking for more
information after this, you should check out Professional ASP.NET 4 in C# and VB by Bill Evjen,
Scott Hanselman, and Devin Rader. Weighing in at over 1,600 pages, this is the best and most
comprehensive resource available to web developers who are building applications on the latest
version of ASP.NET.
21
asP.neT MVC
what’s in this chaPter?
.
Understanding the Model-View-Controller design pattern
.
Developing ASP NET MVC applications
.
Designing URL routes
.
Validating user input
.
Customizing the ASP NET MVC View templates
.
Integrating with jQuery
When Microsoft introduced the first version of the .NET Framework in 2002 it added a new
abstraction for the development of web applications called ASP.NET Web Forms. Where
traditional Active Server Pages (ASP) had up until this point operated like simple templates
containing a mix of HTML markup and server-side code, Web Forms was designed to bring
the web application development experience closer to the desktop application programming
model. This model involves dragging components from a toolbox onto a design surface and
then configuring those components by setting property values and writing code to handle
specific events.
Although Web Forms has been and continues to be very successful, it is not without criticism.
Without strong discipline it is easy for business logic and data-access concerns to creep into
the user interface, making it hard to test without sitting in front of a browser. It heavily
abstracts away the stateless request/response nature of the Web, which can make it frustrating
to debug. It relies heavily on controls rendering their own HTML markup, which can make it
difficult to control the final output of each page.
In 2004, the release of a simple open source framework for building web applications
called Ruby on Rails heralded a renewed interest in an architectural pattern called
Model-View-Controller (MVC). The MVC pattern divides the parts of a user interface
into three classifications with very well-defined roles. This makes applications easier to test,
evolve, and maintain.
438
.
chaPter 21 ASp.neT mVc
Microsoft first announced the ASP.NET MVC framework at an ALT.NET conference in late 2007.
This framework allows you to build applications based on the MVC architecture while taking
advantage of the .NET framework’s extensive set of libraries and language options. ASP.NET
MVC has been developed in a very open manner with many of its features shaped by community
feedback. In fact, in April 2009 the entire source code for the framework was release as open source
under the Ms-PL license.
Microsoft has been very careful to state that ASP.NET MVC is not a
replacement for Web Forms. It is simply an alternative way of building web
applications that some people will find preferable. Microsoft has made it very
clear that it will continue to support both ASP.NET Web Forms and ASP.NET
MVC into the future.
Model View controller
If you have never heard of it before you might be surprised to learn that this “new” Model-View-
Controller architectural pattern was first described in 1979 by Trygve Reenskaug, a researcher
working on an implementation of SmallTalk.
In the MVC architecture, applications are separated into the following components:
.
Model: The model consists of classes that implement domain-specific logic for the application.
Although the MVC architecture does not concern itself with the specifics of the data access
layer, it is understood that the model should encapsulate any data access code. Generally, the
model will call separate data access classes responsible for retrieving and storing information
in a database.
.
View: The views are classes that take the model and render it into a format where the user
can interact with it.
.
Controller: The controller is responsible for bringing everything together. A controller
processes and responds to events, such as a user clicking a button. The controller maps these
events onto the model and invokes the appropriate view.
These descriptions aren’t really helpful until you understand how they interact together. The request
life cycle of an ASP.NET MVC application normally consists of the following:
1 The user performs an action that triggers an event, such as entering a URL or clicking a
button. This generates a request to the controller.
2 The controller receives the request and invokes the relevant action on the model. Often this
will cause a change in the model’s state, although not always.
3 The controller retrieves any necessary data from the model and invokes the appropriate
view, passing it the data from the model.
4 The view renders the data and sends it back to the user.
The most important thing to note here is that both the view and controller depend on the model.
However, the model has no dependencies, which is one of the key benefi ts of the architecture. This
separation is what provides better testability and makes it easier to manage complexity.
Different MVC framework implementations have minor variations in the
preceding life cycle. For example, in some cases the view will query the model
for the current state, instead of receiving it from the controller.
Now that you understand the Model - View - Controller architectural pattern, you can begin to apply
this newfound knowledge to building your fi rst ASP.NET MVC application.
GettinG started with asP net MVc
This section details the creation of a new ASP
.NET MVC application and describes some of
the standard components. To create a new MVC
application, go to File . New Project and select
ASP.NET MVC 2.0 Application from the Web
section. Once you give a name to the project and
select OK, Visual Studio asks if it should create
a unit test project for the application as shown
in Figure 21 - 1. Although this is not required it is
highly recommended because improved testability
is one of the key advantages of using the MVC
framework. You can always add a test project
later on if you want.
Visual Studio 2010 is able to create test projects for MVC applications using a
number of unit testing frameworks. The default choice (shown in Figure 21 - 1) is
to use the built - in unit testing tools in Visual Studio. If you prefer to use a
different unit testing technology, see the vendor for instructions on how to add
to this list.
When an ASP.NET MVC application is fi rst created, it generates a number of fi les and folders.
In actual fact, the MVC application that is generated from the project template is a complete
application that can be run immediately.
The folder structure that is automatically generated by Visual Studio is shown in Figure 21 - 2 and
includes the following folders:
. Content: A location to store static content fi les such as CSS fi les and images.
. Controllers: Contains the Controller fi les. Two sample controllers called HomeController
and AccountController are created by the project template.
Getting started with asP.neT MVC . 439
fiGure 21 - 1
440
.
chaPter 21 ASp.neT mVc
.
Models: Contains model files. This is also a good place to store
any data access classes that are encapsulated by the model. The
MVC project template does not create an example model.
.
Scripts: Contains JavaScript files. By default, this folder
contains script files for JQuery and Microsoft AJAX along
with some helper scripts to integrate with MVC.
.
Views: Contains the view files. The MVC project template
creates a number of folders and files in the Views folder.
The Home subfolder contains two example view files that
are invoked by the HomeController. The Shared subfolder
contains a master page that is used by these views.
Visual Studio also creates a Default.aspx file, which is simply a
placeholder that is needed to ensure IIS loads the MVC application
correctly. There is also a Global.asax file, which is used to configure
the routing rules (more on that later).
Finally, if you elected to create a test project this will be created
with a Controllers folder that contains two unit test stubs for the
HomeController and AccountController, respectively.
Although it doesn’t do much yet, you can run the MVC application by pressing F5. When it opens
in Internet Explorer it will first render the Index view with a link that allows you to navigate to the
About view. Neither of these views is particularly interesting, because they just render static content.
choosinG a Model
In the previous section it was noted that the MVC
project template does not create a sample model for you.
In fact, the application is capable of running without a
model altogether. While in practice your applications
are likely to have a full model, MVC provides no
guidance as to which technology you should use.
This gives you a great deal of flexibility.
The model part of your application is an abstraction of
the business capabilities that the application provides.
If you are building an application to process orders or
organize a leave schedule, your model should express
these concepts. This is not always easy. It is frequently
tempting to allow some of these details to creep in the
View-controller part of your application.
The examples in this chapter use a simple LINQ to SQL
model based on a subset of the AdventureWorksDB
sample database as shown in Figure 21-3. You
can download this sample database from http://
msftdbprodsamples.codeplex.com/.
fiGure 21-2
fiGure 21-3
Controllers and action Methods .
441
The next section explains how you can build your own controller, followed by some interesting
views that render a dynamic user interface.
controllers and action Methods
A controller is a class that responds to some user action. Usually, this response involves updating
the model in some way and then organizing for a view to present content back to the user. Each
controller is capable of listening for and responding to a number of user actions. Each of these is
represented in the code by a normal method referred to as an action method.
Begin by right-clicking the Controllers folder
in the Solution Explorer and selecting Add .
Controller to display the Add Controller dialog
shown in Figure 21-4. This simple dialog allows
you to select a name for your new controller.
By convention, the MVC framework requires
that all controller classes have names that end
in “Controller,” so this part is already filled in
for you. There is also a checkbox allowing you
to add some simple functionality. We’ll ignore
this for now and come back to it later. Give the new controller a name of ProductsController and
click Add.
fiGure 21-4
You can quickly add a controller to your project by using the Ctrl+M, Ctrl+C
shortcut as well.
New controller classes inherit from the System.Web.Mvc.Controller base class, which performs
all of the hefty lifting in terms of determining the relevant method to call for an action and mapping
of URL and POST parameter values. This means that you can concentrate on the implementation
details of your actions, which typically involves invoking a method on a model class and then
selecting a view to render.
A newly created controller class will be populated with a default action method called Index. You
can add a new action simply by adding a public method to the class. If a method is public, it will be
visible as an action on the controller. You can stop a public method from being exposed as an action
by adding the System.Web.Mvc.NonAction attribute to the method. The following listing contains
the controller class with the default action that simply renders the Index view, and a public method
that is not visible as an action:
c#
public class ProductsController : Controller
{
//
// GET: /Products/
public ActionResult Index()
442 . chaPter 21 ASp.neT mVc
{
return View();
}
[NonAction]
public void NotAnAction()
{
// This method is not exposed as an action.
}
}
Vb
Public Class ProductsController
Inherits System.Web.Mvc.Controller
'
' GET: /Products/
Function Index() As ActionResult