Getting started with ASP.NET MVC (Preview)

The Preview 3 build of the ASP.NET MVC framework was recently released and seems to be gathering a lot of excitement in the .NET community. As I’m reading and learning more about it I wanted to start a series of posts that gives you a quick understanding of the core features that the framework offers to get you started ASAP.

What is ASP.NET MVC?
ASP.NET MVC is a framework for developing web applications using a model-view-controller (MVC) based architecture in ASP.NET.

The Model View Controller (MVC) pattern is a methodology for separating an application’s data, presentation, and user input into specialized components. [Figure 1]
- The Model represents the components of the application that are responsible for maintaining state
- The View represents the presentation or user interface that the user interacts with
- The Controller is the bridge between the user and the application and is responsible for executing application logic


[Figure 1]

The Controller is responsible for input from the user whereas the View is responsible for output to the user. Both the view and the controller depend on the model; however, the model depends on neither the view nor the controller. Not all actions by the user or input necessarily means there will be interaction with the Model, it could be just a Controller-View interaction that is then sent back to the user. In other words, if the user does not require any change of data and only wants UI changes then the Controller will intercept any input then pass it to the View without any contact with the Model.

How does this MVC pattern apply to our web-based environment or ASP.NET? Let's look at [Figure 2] and study the process flow.


[Figure 2]

A. The user submits a browser request via our web application
B. An HTTP request is sent to the server
C. The Controller class receives the request depending on the type of request:
1. Interacts with the Model
- Initializes and calls the Model (i.e. Data)
- Posts/Retrieves data to/from the Model
- Selects a View
- Renders page
2. Bypasses the Model and directly calls the View
- Selects a View
- Renders page
D. The server then sends back that HTTP Response back to the user

If you compare this to classic ASP.NET (Web Forms), in that model the View (ASPX) is responsible for both the input and output.

Now what’s the reason to use ASP.NET MVC instead of sticking with the existing ASP.NET framework? Arguably the most important reason is testing; ASP.NET MVC attempts to overcome the challenge of fully testing a WEB UI. Using ASP.NET web forms simplifies the development process with many built-in user controls but at the same time encourages a developer to include a lot of the logic to the presentation layer and therefore makes it much harder to test since you have to run the page itself in a browser to test the full functionality. In ASP.NET MVC, you can call the Controller class separately and simulate the tests without having to view the web pages in the browser.

The other main reason is the clear separation of responsibilities between the different layers. As mentioned, in traditional web forms unless you have strict rules that are established for all developers to follow, you are tempted to add more logic to the presentation layer than is really needed and end up making your application harder to re-use, test, maintain etc. In one of my recent projects, we used a guidance package which enforced many of these rules and minimized mixing of presentation, business and data layers but there’s always the possibility of throwing in some business logic in the presentation layer.

The biggest change from a developer’s point of view is that with the ASP.NET MVC Framework we’re not using postbacks, viewstate or page lifecycle events anymore. In addition, URLs do not point to a physical file location but instead to a Controller class, these concepts will get clearer when we look at the sample in the next section.

Alternatively if you plan to work with Web Forms, the Microsoft patterns and practices group developed a Web Client factory that uses the MVP (Model-View-Presenter) pattern to improve both testing and logic separation of traditional web forms, you can download it here. In short, what the MVP model does is separates the View (ASPX) from the Model using a Presenter so everything goes through the Presenter; For testing purposes you can call the Presenter without having to call the page (View in this case). The downside is you’re still using the Web form Postback model so you’ll have to forward all these events from the View to the Presenter.

In ASP.NET MVC, the current implementation lacks the drag and drop validation controls so you lose some of the functionality you’re used to with web forms, you’ll have to develop these on your own. There have been efforts to start developing such a library as you can see here. It’s probably a good bet that there will be MVC-specific controls that will be included in the full release of ASP.NET MVC or in a future version. Worth mentioning that ASP.NET MVC is not intended to replace web forms, both will be developed in parallel.

Listed below are the Pros & Cons of ASP.NET MVC (as of Preview 3 version) for someone who has spent most of his time working on classic ASP.NET Web Forms which applies to the large majority of .NET developers. Each topic listed here deserves a separate post so I won’t be going into a lot of detail right now but here are the key things to remember:

Pros
- Seperation of Concerns
- Testability
- Test-driven Development
- Highly Extensible
- URL Routing (custom URLs)
- Full control of HTML
- Supports existing Authentication / Roles / Caching / Session Management / Configuration / Master Pages / User Controls

Cons
- No Postbacks i.e. different from Web Forms
- Lack of Page life-cycle events
- No Viewstate support
- Lack of controls i.e. validation controls
- Lose direct relationship between URL and physical file (ASPX)
- Some applications might take longer time to develop vs Webforms i.e. editable grids, treeviews, 3rd party controls etc.

For more information on the MVC pattern, check this article on MSDN.

Building your first ASP.NET MVC application
Now that you understand the basics, let’s start with our sample application. You can download the ASP.NET MVC package here. The .NET Framework 3.5 and Visual Studio 2008 are also required.

After you’ve downloaded the framework, open Visual Studio 2008 and you should see an ASP.NET MVC application template, please select it and select your folder location then click OK. [Figure 3]


[Figure 3]

The next window that will ask if you want to create a unit test Project so you can already see why automated testing is one of the core framework features. In the Test Framework dropdown you can select your desired Testing framework; in this case I will be using the default Visual Studio unit test, click OK.

Your solution is now created, before we look at the solution structure and the code itself; let’s just start the web application. It only consists of 2 pages, Home and About Us. The key thing to notice is that the URL doesn’t point to a physical file. [Figure 4][Figure 5]


[Figure 4] http://localhost/Home


[Figure 5] http://localhost/Home/About

Now check the solution structure, it looks like your typical web ASP.NET web application but has a series of new folders described below [Figure 6].


[Figure 6]

The Default.aspx file is there for IIS purposes so you should keep it, it’s mostly a placeholder that redirects to the Home URL.

How did the http://localhost/Home/About url know what page to call? Open the global.asax file [Figure 7], the Application_Start() method is calling the RegisterRoutes method. In the RegisterRoutes method, “{controller}/{action}/{id}” defines how your URLs should look. The controller points to the controller class, the action is one of the methods inside the controller class and the id is the parameter that is passed to that method. In addition, there is a default path that is set {controller=”Home”, action=”Index”, id=””} so you are redirected to the Home controller class Index method which then renders the Index.aspx view. Worth mentioning that you can change the URL pattern to any desired format.


[Figure 7]

If you open the HomeController.cs class [Figure 8] under the Controllers folder, you’ll see both the Index() and About() methods. Each renders the corresponding ASPX page in the Views folder. Both the /Home and the /Home/About URLs point to the same HomeController class but to different methods that then point to different views.

URL Controller class Controller method View
/Home HomeController.cs Index() Index.aspx (under the Views/Home subfolder)
/Home/About HomeController.cs About() About.aspx (under the Views/Home subfolder)

Note: The HomeController class derives from the System.Web.MVC.Controller base class, the ViewData collection contains the data that will be passed to the Views and the Index() and About() methods return ActionResult.


[Figure 8]

Last but not least, open the HomeControllerTest.cs class under the test project. Here you can call your Controller class without worrying about the UI so you can automate all your tests right away and inside your solution, something that can’t be done so easily with traditional web forms.


Next Steps
This post was to get you started with a basic understanding of what ASP.NET MVC offers. In future posts, I’ll focus on specific functionality and get into more details about a particular feature.

0 comments: