Targeting the Enterprise with ASP.NET MVC 2.0

ASP.NET MVC 2.0 is the latest Microsoft framework for building web applications on top of the .NET framework 2.0, 3.0, 3.5 etc.

MVC stands for Model, View, and Controller, a design pattern that is widely accepted throughout the development industry. You can download MVC 2.0 Beta from the following URL. http://www.microsoft.com/downloads/details.aspx?FamilyID=4817cdb2-88ea-4af4-a455-f06b4c90fd2c&displaylang=en

Microsoft has also published source code of the MVC Framework, which can be downloaded from Codeplex. http://aspnet.codeplex.com/releases/view/39978

For a little perspective, MVC Framework is a part of Visual Studio 2010 Beta 2, and this will be included with the VS 2010 final version as well, which will be launched in April. MVC 2.0 Framework is still a beta version and bug fixes are still in progress. Hopefully we will get the fully tested version very soon. A year ago, the ASP.NET MVC source code was released under the Microsoft Public License.

The Model, View, Controller Design Pattern

Model, View, Controller is an architectural approach to separate application business and model objects from the user interface. View is the output visible to the users. For an ASP.NET application it would be .ASPX, HTML pages, and controls embedded in these pages. View represents the look and feel of an application and totally isolates the business data processing.

The Model consists of actual data processing elements like all database related operations. The Model also feeds data to the View. It is designed in such a way that it can interact and pass data to many views and avoid code redundancy. Model responds to the request made by controllers and also notifies views to update their display with new data.

Controllers are responsible for triggers or actions. Controllers are nothing but events raised by users like mouse click, keyboard key press, etc. Most of the time, events are raised by users while interacting with the View. These triggers do make changes, calling methods defined in Model and update Model state. Model also notifies View to refresh its display.

HTTP request processing for ASP.NET and MVC applications are different. For MVC applications, HTTP requests are routed based on the route information stored in RouteTable object.

Creating an MVC 2.0 New Web Application

When you select New Project Option in the Visual Studio 2008 editor, the following popup comes up for selecting project type. If MVC 2.0 is installed in your machine, you will get two Project Types: 1) ASP.NET MVC 2 Web Application, and 2) ASP.NET MVC 2 empty Web Application. On the right side dropdown you can select .NET Framework Version, on top of which you want to execute your MVC Web Application.

Figure 1.Different MVC project templates.

For this example I have selected ASP.NET MVC 2 Web Application and .NET Framework 3.5.

On the next screen you will be asked to include Unit Test Project to your solution. Visual Studio Unit test Framework is included with MVC 2.0 framework and that would be the default selection. If you want to include a custom unit testing framework like Nunit, install the Library and locate the following registry key.

HKEY_LOCAL_MACHINESOFTWAREVisualStudio9.0MVCTestProjectTemplates

Under TestProjectTemplates, add the Template name like Nunit. Under the test framework, add a key for the code language, such as “C#” or “VB”. Also add the following values under test framework. * AdditionalInfo — This is optional. Enter a URL that links to a Web page about the test framework.
* Package — This is optional. Enter the path of a Visual Studio 2008 package.
* Path — Enter the path where the template is located. Generally its in %Program Files%Microsoft Visual Studio 9.0Common7IDEProjectTemplates.
* Template — name of the test template.
* TestFrameworkName – Enter the name of the test framework that will appear in the Test framework list.

Figure 2.Adding a Unit Test Project to your MVC applications.

Click Ok to Create MVC Test Project. Now you will be able to see two projects — MVC main project and MVC test project under your main solution(MyMvcSample).

Figure 3.The folder structure of your MVC application.

The default folder structure for MyMvcSample will be …

* App_Data — This folder contains data files including MDF files, XML files, or data storage files. Basically this folder is used for storing the local database.

* Content — Repository for all static files like Cascading Style Sheets (CSS), Images etc.

* Controllers — All controller class files as (.CS or .VB). As per MVC naming convention all the controller files should end with word “Controller,” for example AccountController, LoginController etc.

* Models — All Model classes (CS or .VB). This folder contains classes that defines objects and logic for interacting with data store. If you are developing separate class libraries for you Model then include the Dll’s in this folder.

* Scripts — Recommended location for all client side scripting objects like JavaScript and VB script files. By default MVC 2.0 application have some preexisting Javascript files. JQuery script and client side validation Library is used for simplifying HTML document traversing, intellisense, event handling, animating, and Ajax interactions for rapid web development. By default, the JQuery scripts are not included in the existing and new Views. To add, use the following script block.

 ???????? ?

Also you will find Script files generated by the Script# tool (http://projects.nikhilk.net/).It’s a free tool that generates JavaScript by compiling C# source code. This tool enables you to leverage the productivity of C#, the Visual Studio IDE, and .NET tools and apply them to your Ajax development.

Debugging your MVC 2.0 Web Application

The default entry point for all MVC applications is Application_Start event defined in Global.asax. But if you put in a breakpoint, the program control will never stop there. To start debugging from the Application_Start event, you need to change the solution properties. In the following screen-shot you can see 3 different projects under the solution and by default all checked for Build. You need to deselect the build option for all the projects added in your solution except your MVC Project.

Figure 5.The Change Solution Property for supporting debugging.

If you see code under Application_Start () event, the first function call is AreaRegistration.RegisterAllAreas ().

In MVC 2.0, the concept of area is to divide your large project in different modules or small projects. Each Area can consist of its own Contents, Controllers, Views, and Scripts etc. For example, if you are working in a Factory Automation Project, your sub projects/modules can be Accounts, Inventory, and Security etc. Now to register all these modules altogether you need to call AreaRegistration.RegisterAllAreas () in the parent project, and the best place to write that is in the Application_Start () event.

Routes is a static property of the RouteTable class mentioned in the parameter of RoughRegisterRoutes Procedure call. This property contains all the routes in an application. You can also add a route, from an event handler for the Application_Start event in the Global.asax file.

When an MVC application handles a request, the application iterates through the collection of routes in the Routes property to find the route that matches the format of the URL request.

The following code describes how you can add a route.

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ???RegisterRoutes(RouteTable.Routes)End SubShared Sub RegisterRoutes (ByVal routes As RouteCollection) ???Dim Pattern As String ???Dim Routecategory As Route ???Pattern = "Category/{action}/{categoryName}" ???Routecategory = New Route (Pattern, New CategoryRouteHandler) ???routes.Add(Routecategory)End Sub

The System.Web.Routing assembly is responsible for URL routing supported in MVC application. The following section of your Web.config file have relevant routing information –system.web.httpModules,system.web.httpHandlers, system.webserver.modules and system.webserver.handlers. Routing has been introduced in .NET Framework SP1, to enable developers to use URL’s that do not have to map to a physical file of the website. In a route, placeholders can be defined by enclosing them in braces {and}. The / character is interpreted as a delimiter when the URL is parsed. In our project “{controller}/{action}/{id}” is the pattern where default controller is Home i.e physical file HomeController.vb and action Index means the Function Index() declared in the HomeController.

routes.MapRoute( _ ???????????"Default", _ ???????????"{controller}/{action}/{id}", _ ???????????New With {.controller = "Home", .action = "Index", .id = ""} _        )

To enable Routing in your web application, you must configure the Web.config file. The first thing you need to do is to add System.Web.Routing assembly under the assemblies section.

Next, if your application runs under IIS 6.0 or IIS 7.0 add UrlRoutingModule module under httpModules Section.

If your application under IIS 7.0 is in integrated mode, the following UrlRoutingModule needs to be added under module section.

Also, you have to add UrlRoutingHandler class under Handlers element.

Now, if you see the Index () function carefully of your HomeController the 1st statement is?.

  ViewData("Message") = "Welcome to ASP.NET MVC!"

ViewData class is used in MVC applications to pass data from Controller to View. This class is a hybrid of two classes; it is inherited from the base Dictionary class. Dictionary class can be represented as string and Object combinations (Dictionary). That’s how the ViewData class can also work like a generic class. You can add a key and value pair combination to Dataview class, which looks like:

ViewData("Message") = "I am new to MVC Framework."

The next function call View () — member of System.Web.Mvc.Controller class Creates a System.Web.Mvc.ViewResult object that renders a view to the response.

Conclusion

The best benefits of using a MVC Framework is that it helps enforce a clean separation between the models, views, and controllers within a Web application. It is easier to maintain clean separation code/applications for a developer as well as a tester perspective. MVC Framework also provides test driven development methodology — developers can automatically generate unit test cases that minimizes development time.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: