06 Jan 2009

Introducing the ASP.NET MVC (Part 4) – Your First ASP.NET MVC Project

6 Comments Uncategorized

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

Your First ASP.NET MVC Project

To create your first ASP.NET MVC Project, you only need the prerequisites listed in the previous section.  To start, you first need to open Visual Web Developer 2008 or any version of Visual Studio 2008.

For the purpose of this section I will be using Visual Studio 2008 Team Development Edition.  I have, however, verified that this process works on Visual Web Developer 2008 SP1, Visual Studio 2008 Professional, and Visual Studio 2008 Team Development Edition.

After Visual Studio is open we need to create a new project (File > New > Project), see Figure 2-16 for an example.

Figure 2-16

Figure 2-16

Doing this will put you in the New Project screen, which you will then select your preferred language (in our case Visual C#).  From there we need to select Web @@> ASP.NET MVC Web Application, as depicted in Figure 2-17.

Figure 2-17

Figure 2-17

I am going to leave all the project configuration fields set to their default values as shown in Figure 2-17, you may configure them however you desire.  When you are done click OK, and you will see the screen shown in Figure 2-18.

Figure 2-18

Figure 2-18

You have probably not seen a screen like this before, even if you have done ASP.NET Web Forms development.  It is totally new to the ASP.NET MVC project creation process, and it automatically creates a unit testing project based on the default MVC project.

As an added feature it also allows you to select the testing framework that you would like to use, even non-Microsoft ones, such as NUnit, MbUnit, XUnit, Visual Studio Unit Test, and any others that decide to provide an interface to this Visual Studio process.

You can choose to create a unit project, or wait till a later time if desired.  For the purpose of this demonstration I am going to create a unit test project using MbUnit v3 from the drop down.  When you are done click OK, and you will see a Solution Explorer that looks like Figure 2-19.

Figure 2-19

Figure 2-19

This is what the default folder and file structure looks like for the ASP.NET MVC project, it has a separate folder for Models, Views (as seen in Figure 2-21), and Controllers (as seen in Figure 2-20).  As well as a set of default folders for storing JavaScript, CSS, or anything else you would want to deliver from your web application (as seen in Figure 2-22).

Figure 2-20

Figure 2-20

There are two controllers created by default.  The HomeController is used to render the home page and the about page.  The AccountController is used to authenticate a user with the standard ASP.NET membership provider.  These two controllers provide you everything you need to create a very basic web application.

Figure 2-21

Figure 2-21

For the views there is a mirroring of the controllers created.  One for Account and another for Home, in these folders there are aspx files that are call views.  Each of these views mirror an action method from the controller, by default.  As you will see later in this book there is a many to many relationship between the views and action methods.  In that an action method can map to multiple views and a view can have multiple action methods that use it.  Let’s not get to in-depth about the mapping of views and action methods at this point, because we will cover this in great detail later in this chapter and future chapters when implementing our application.

There is also a shared folder called Shared, which is, for lack of a better word, shared between all of the controllers and can be called by any of the controllers in the project.

The last thing I want to talk about before we move on to the rest of the files in the solution, is what appears to be a rouge Web.config file located under the Views directory.  This is a deliberate and strategic Web.config that is used, in addition to the one in the root, to block access to all the aspx files from getting accessed directly.  This Web.config file contains the following configuration information:

<?xml version="1.0"?>
<configuration>
	<system.web>
		<httpHandlers>
			<remove verb="*" path="*.aspx"/>
			<add path="*.aspx" verb="*" type="System.Web.HttpNotFoundHandler"/>
		</httpHandlers>
	</system.web>

	<system.webServer>
		<validation validateIntegratedModeConfiguration="false"/>
		<handlers>
			<remove name="PageHandlerFactory-ISAPI-2.0"/>
			<remove name="PageHandlerFactory-ISAPI-1.1"/>
			<remove name="PageHandlerFactory-Integrated"/>
			<add name="BlockViewHandler" path="*.aspx" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
		</handlers>
	</system.webServer>
</configuration>

It contains both configuration information for IIS 7, <system.webServer />, and IIS 6 and lower, <system.web />.  So you will be covered on which ever server you decide to deploy your MVC application to.

Figure 2-22

Figure 2-22

The rest of the solution files, includes JavaScript, Style Sheets, and other ASP.NET files that you should be familiar with.  The JavaScript files that are included by default are Microsoft AJAX and jQuery, as well as debug version of the files.

In the Fall of 2008, Microsoft announced a partnership with jQuery (www.jquery.com) to provide support and deliver jQuery with Visual Studio 2010 and some key projects.  One of the key projects that jQuery will be delivered with, is ASP.NET MVC.

If you are going to be using jQuery heavily in your application, as we are in this book, I highly recommend that you download the latest version of jQuery and the Visual Studio Intellisense Documentation for jQuery.  jQuery is constantly being developed and new features are getting added all the time, so it really pays to be running the latest version, so be sure to get the latest production and development files:

http://www.jquery.com

There are some standard ASP.NET files that we have all seen before, but I would like to take this opportunity to give you a quick overview of the purpose of the Global.asax and Default.aspx files.  These two files have a special purpose in an MVC application that you should be made aware of.

Global.asax

This is a standard ASP.NET file.  MVC takes advantage of the file to initialize all the URL routes, for mapping actions and controllers to URL’s, when the application is first started, using the Application_Start event handler.

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

	routes.MapRoute(
		"Default",
		"{controller}/{action}/{id}",
		new { controller = "Home", action = "Index", id = "" }
	);
}

protected void Application_Start()
{
	RegisterRoutes(RouteTable.Routes);
}

Default.aspx

This is a standard ASP.NET file.  It is not necessary on IIS 7, because of IIS 7′s integrated pipeline.  However you should not worry about it being present on and IIS 7 MVC application because, it will not interfere with the execution of the code.  The sole purpose, of this file, is to handle root requests on IIS 6 and lower, it does this using the Page_Load event handler of the page and forcing the request through the MvcHttpHandler, instead of rendering the page, which is empty.  The Page_Load event handler is shown in the code below.

public void Page_Load(object sender, System.EventArgs e)
{
	HttpContext.Current.RewritePath(Request.ApplicationPath);
	IHttpHandler httpHandler = new MvcHttpHandler();
	httpHandler.ProcessRequest(HttpContext.Current);
}

The final thing I want to cover is what the default ASP.NET MVC application design looks like when running in a browser, you can see an example of this in Figure 2-23.

Figure 2-23

Figure 2-23

It is a pretty basic layout, but it is a good example of the Home and Account controllers and can be used to render to and interact with the browser.

In the rest of this chapter, we are going to cover the basics of the ASP.NET MVC Framework, with a specific focus on the Model, View, and Controller.  So let’s get started.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009

05 Jan 2009

Introducing the ASP.NET MVC (Part 3) – Installing the Prerequisites

8 Comments Uncategorized

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

Installing the Prerequisites

To start developing ASP.NET MVC and to run the code in this book, you will need the following prerequisites installed on your system:

  1. Visual Web Developer 2008 Express Edition SP1
    http://www.microsoft.com/express/download/
  2. SQL Server 2005 Express Edition
    http://www.microsoft.com/express/sql/download/
  3. Micorosft.NET Framework 3.5 SP1
    http://msdn.microsoft.com/en-us/netframework/
  4. Microsoft ASP.NET MVC
    http://www.asp.net/mvc/

You can cover prerequisites 1-3 by downloading just the Visual Web Developer 2008 Express Edition installation file, which includes .NET 3.5 SP1 by default and SQL Server 2008 Express Edition as an optional add-on during the install process.

If you have already installed all of the software above, or have an edition of the software that is better you may skip to the Your First ASP.NET MVC Project section.

Read more

29 Dec 2008

Introducing the ASP.NET MVC (Part 2) – ASP.NET MVC vs. ASP.NET Web Forms

16 Comments Uncategorized

This is a continuation of my Introduction to ASP.NET MVC series.  As I outlined before this is in an effort to write the book and keep blogging, I decided to write/blog the last chapter, Chapter 2.  I am doing this so I can receive feedback on this chapter as early as possible.  Because this chapter, in my opinion, is probably the most critical of the book, it defines the context around ASP.NET MVC and how it differs from ASP.NET Web Forms, as well as giving a historical perspective of the MVC pattern.

In the next several posts we will cover the following parts of Chapter 2 from the book:

by Nick Berardi

New: $31.49
This item has not yet been released. You may order it now and we will ship it to you when it arrives.

ASP.NET MVC vs. ASP.NET Web Forms

As you have seen, in the previous section, and can probably imagine MVC is going to be an architectural pattern that is going to be around for the foreseeable future, especially on the web.  So it is very important to internalize and understand the major differences between ASP.NET MVC and the older ASP.NET Web Forms.

ASP.NET Web Forms

Starting with the .NET Framework Version 1.0, in January 2002, Web Forms was Microsoft’s first real attempt to provide a first class web application layer that was both robust and flexible enough to meet the demands of the web at that time.  ASP.NET Web Forms has proven to be a mature technology that runs small and large scale websites alike.  Web Forms, was built around the Windows Form construction, where you had a declarative syntax with an event driven model.  This allowed visual designers to take full advantage of the drag and drop, WYSIWYG, interface that they had become accustom to under Windows Forms development in Visual Studio 6.0.  In that they only needed to drop controls onto the ASP.NET page and then wire up the events, as was common in Visual Basic 6.0 development at the time. This made Web Forms a natural choice for Windows Forms developers, because the learning curve was low and the need to understand HTML and many of the web centric technologies almost zero.  Web Forms have many strengths and weaknesses:

Strengths
  • Mature technology
  • Provides very good RAD development capabilities
  • Great WYSIWYG designer support in Visual Studio
  • Easy state management
  • Rich control libraries from Microsoft and third party vendors
  • Abstracts the need to understand HTTP, HTML, CSS, and in some cases JavaScript
  • ViewState and PostBack model
  • A familiar feel to Windows Forms development

Web Forms has grown so much since 2002 because it has the ability to do great things that are often much harder to accomplish in other frameworks.

Weaknesses
  • Display logic coupled with code, through code-behind files
  • Harder to unit test application logic, because of the coupled code-behind files
  • ViewState and PostBack model
  • State management of controls leads to very large and often unnecessary page sizes

Web Forms is not all roses and buttercups, there are some serious setbacks that usually show up when you are trying to optimize your code for scalability, the biggest problems are the ViewState and PostBack model.  ViewState is a way to store the state of the controls, such as data, selections, etc, which is needed to preserve the Windows Form like development habits of the developers.  ViewState was necessary, because the web is a stateless environment meaning that when a request comes in to the server it has no recollection of the previous request.  So in order to give state to a stateless environment you need to communicate the previous state back to the server, in Web Forms this was accomplished using hidden <input /> fields that can become ridiculously large. This increased size becomes apparent when server controls such as GridView are added to the page.  PostBack was another creation to facilitate the Windows Form development feel, it renders JavaScript for every subscribed event, which leaves web developer less control over how the browser communicates with the server.

ASP.NET MVC

ASP.NET was often overlooked as a viable platform for modern highly interactive websites that required a very granular control over the output of the HTML, because of the lack of control over the rendered HTML.  This granularity of control was sacrificed in Web Forms to make if more like Windows Forms development, in other words easier for the drag and drop developers.  This lack of control over the HTML rendering forced developers to move the platforms such as PHP and Ruby on Rails, which offered the level of control they required and the MVC programming model that provided a necessary separation of concerns for their highly complex web applications.

This led Microsoft to announce in the Fall of 2007 that they were going to create a platform based off of the core of ASP.NET that would compete against these other popular MVC web centric platforms.  Microsoft implemented ASP.NET MVC to be a modern web development platform that gives a ‘closer to the metal’ experience to the developers that program with it, by providing full control and testability over the output that is returned to the browser.  This is the main and most important different between Web Forms and MVC, in my opinion.  MVC has many strengths and weaknesses

Strengths
  • Provides fine control over rendered HTML
  • Cleaner generation of HTML (well as clean as you keep it)
  • Clear separation of concerns
  • Provides application layer unit testing
  • Can support multiple view engines, such as Brail, NHaml, NVelocity, XSLT, etc.
  • Easy integration with JavaScript frameworks like jQuery or Yahoo UI frameworks
  • Ability to map URLs logically and dynamically, depending on your use
  • RESTful interfaces are used by default (this helps out with SEO)
  • No ViewState and PostBack model
  • Supports all the core ASP.NET features, such as authentication, caching, membership, etc.
  • Size of the pages generated typically much smaller because of the lack of the ViewState
Weaknesses
  • Not event driven by the framework, so it maybe more difficult for ASP.NET Web Form developers to understand
  • Requires the need to understand, at least at the basic level, HTTP, HTML, CSS, and JavaScript
  • Third party library support is not as strong
  • No direct upgrade path from Web Forms
  • No ViewState and PostBack model (makes it more difficult to preserve state)

As you can see the pros and cons of MVC have to be weighed just as much as Web Forms, and MVC is not always the logical choice.

How do I choose?

It’s up to you to decide and you choice needs to be weighted with a number of other factors, such as team and application requirements, when deciding which ASP.NET technology to implement.  I have developed the following worksheet that will hopefully help you decide, when you need to make this decision.

The Worksheet

This worksheet is meant to be a guide for when you are trying to choose between Web Forms and MVC.  The values in the Value column are representations of how easy it would be to accomplish the requirement in either MVC or Web Forms.

The values range from 0 to 30, zero being no effort to implement and 30 requiring a great amount of effort to implement.  If the value is positive then it is an advantage to MVC, if the value is negative then it is an advantage to Web Forms.  For example if the value is, +4, then the requirement is more suited for MVC, and it would take a little work to get it to work as easily in Web Forms.  Alternatively, if the value is, -25, then the requirement is definitely suited for Web Forms, and it would take a lot of work to get the requirement to work with MVC.

Requirement Value Selection
Clean HTML Rendering

+4

Use RAD Designers

-5

Use TDD (Test Driven Design)

+8

Testability

+7

Data-heavy application

-10

Upgrade from Web Forms

-25

Need event-driven model compared to Windows Forms programming model

-7

Work on an Agile Team

+4

Need separation of concerns

+10

Creating a proof of concept or prototype

-6

SEO

+3

RESTful interface

+3

Need to preserve state of request

-2

Building an Internet Application

+3

Building an Intranet Application

-3

Need to support multiple views of the same application through mobile, web, and REST API

+7

Need to use existing third party controls for ASP.NET Web Forms

-10

Need control over the URL that is generated

+5

So after you make your selection and add up all the values, you should end up with a number representing your project.  Check that number against the table below, and you should have your answer as to which technology, MVC or Web Forms, is best for your project and team.

Value Reasoning

< -50

No Brainer, go with Web Forms

-25

Very Strongly Web Forms

-10

Strongly Web Forms

-3

Slightly Web Forms

0

It is a tossup between Web Forms and MVC

+3

Slightly MVC

+10

Strongly MVC

+25

Very Strongly MVC

> +50

No brainer, go with MVC

I want to mention one last thing if you have want to do new development in MVC, but you have to maintain some legacy Web Form pages, you can mix MVC and Web Forms in the same application. You just need to be aware of the differences between the two, and that you probably will not be able to share any of the Web Form front end code with MVC, such as Themes, Master Pages, and User Controls.

As you probably can guess by the name of this book, The Beer House application landed well in to the MVC side of the worksheet.  Which probably doesn’t surprise you if you are reading this book!

Feel free to use the above decision table and modify it for your own teams’ decision process.  The information provided above however should arm you with most of the important information that you need to know when deciding which way your project should go technology wise.

This post is licensed under a different license than the rest of my site. Copyright © Wiley Publishing Inc 2009