Mixing ASP.NET Webforms and ASP.NET MVC

by Maarten Balliauw | March 2009 | Microsoft

Ever since Microsoft started working on the ASP.NET MVC framework, one of the primary concerns was the framework's ability to re-use as many features as possible from ASP.NET Webforms. In this article by Maarten Balliauw, we will see how we can mix ASP.NET Webforms and ASP.NET MVC in one application and how data is shared between both these technologies.

(For more resources on .NET, see here.)

Not every ASP.NET MVC web application will be built from scratch. Several projects will probably end up migrating from classic ASP.NET to ASP.NET MVC. The question of how to combine both technologies in one application arises—is it possible to combine both ASP.NET Webforms and ASP.NET MVC in one web application? Luckily, the answer is yes.

Combining ASP.NET Webforms and ASP.NET MVC in one application is possible—in fact, it is quite easy. The reason for this is that the ASP.NET MVC framework has been built on top of ASP.NET. There's actually only one crucial difference: ASP.NET lives in System.Web, whereas ASP.NET MVC lives in System.Web, System.Web.Routing, System.Web.Abstractions, and System.Web.Mvc. This means that adding these assemblies as a reference in an existing ASP.NET application should give you a good start on combining the two technologies.

Another advantage of the fact that ASP.NET MVC is built on top of ASP.NET is that data can be easily shared between both of these technologies. For example, the Session state object is available in both the technologies, effectively enabling data to be shared via the Session state.

Plugging ASP.NET MVC into an existing ASP.NET application

An ASP.NET Webforms application can become ASP.NET MVC enabled by following some simple steps. First of all, add a reference to the following three assemblies to your existing ASP.NET application:

  • System.Web.Routing
  • System.Web.Abstractions
  • System.Web.Mvc

After adding these assembly references, the ASP.NET MVC folder structure should be created. Because the ASP.NET MVC framework is based on some conventions (for example, controllers are located in Controllers), these conventions should be respected. Add the folder Controllers, Views, and Views | Shared to your existing ASP.NET application.

The next step in enabling ASP.NET MVC in an ASP.NET Webforms application is to update the web.config file, with the following code:

< ?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="false">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Abstractions,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing,
Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing"/>
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
</namespaces>
</pages>
<httpModules>
<add name="UrlRoutingModule"
type="System.Web.Routing.UrlRoutingModule,
System.Web.Routing, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
</configuration>

Note that your existing ASP.NET Webforms web.config should not be replaced by the above web.config! The configured sections should be inserted into an existing web.config file in order to enable ASP.NET MVC.

There's one thing left to do: configure routing. This can easily be done by adding the default ASP.NET MVC's global application class contents into an existing (or new) global application class, Global.asax.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MixingBothWorldsExample
{
public class Global : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}",
// URL with parameters
new { controller = "Home", action = "Index", id = "" }
// Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}

This code registers a default ASP.NET MVC route, which will map any URL of the form /Controller/Action/Idinto a controller instance and action method. There's one difference with an ASP.NET MVC application that needs to be noted—a catch-all route is defined in order to prevent a request for ASP.NET Webforms to be routed into ASP.NET MVC. This catch-all route looks like this:

routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");

This is basically triggered on every request ending in .aspx. It tells the routing engine to ignore this request and leave it to ASP.NET Webforms to handle things.

With the ASP.NET MVC assemblies referenced, the folder structure created, and the necessary configurations in place, we can now start adding controllers and views. Add a new controller in the Controllers folder, for example, the following simpleHomeController:

using System.Web.Mvc;
namespace MixingBothWorldsExample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "This is ASP.NET MVC!";
return View();
}
}
}

The above controller will simply render a view, and pass it a message through the ViewData dictionary. This view, located in Views | Home | Index.aspx, would look like this:

<%@ Page Language="C#"
AutoEventWireup="true"
CodeBehind="Index.aspx.cs"
Inherits="MixingBothWorldsExample.Views.Home.Index" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<div>
<h1><%=Html.Encode(ViewData["Message"]) %></h1>
</div>
</body>
</html>

The above view renders a simple HTML page and renders the ViewData dictionary's message as the page title.

ASP.NET MVC 1.0 Quickly

Sign up for a Packt account to see the rest of this article

Now that you've read a few articles, you might want to consider signing up for a Packt account. It takes a matter of seconds, will give you access to all the articles on PacktPub.com, and once you've signed up you'll be returned here to carry on reading your article.

Furthermore, you'll gain access to nine free ebooks, and be offered a free trial of PacktLib, Packt's online library. Simply enter your details here, or log in to your existing account.

Log in

...or register

"Add View" dialog by
This was very helpful, thank you! One question - i can't see "Add View" button when I right-click on Controller's ActionResult method. Is there any other way to get "Add View" dialog or it's not possible with "integrated" solution?
I know it has been for a while...but by
Thanks for the post. I followed the steps but I hit the error "Viewdata does not exist in the current context" error. Then I find this: http://stackoverflow.com/questions/4677615/could-not-load-type-system-web-mvc-viewpagedynamic-in-asp-net-mvc2-after-publ and add the extra declaration in the web.config and it works for me. Thanks heap. Most inspirational.
IrretenoG by
Very informative post. Thanks for taking the time to share your view with us.
Good Article by
Thanks for the article..
Great Stuff Buddy by
One of the coolest stuff in this area I cam across. Keep the Good work going.
Starts from having a webforms project, then add in MVC, good. by
Good. Works well to. And starts from the opposite direction of what I thought should be done. And it still works. Great!
Good Article by
This article is the perfect starting point on how to add asp.net MVC to the existing Web Application project. Thank you. also thanks to others for identifying those minor mistakes.
missing stuff by
Index.aspx.cs class should inherit from ViewPage
one small thing by
Great article and to the point but aren't you missing <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> from the system.web/compilation/assemblies section? I found I needed it for the pages/namespaces section to work.
Great article - short and really to the point! by
Its not often that I come across articles this good. Keep up the good work mate. If everyone could write this way instead of the old (and useless) ifitwashardtowriteitshouldbehardtoread-paradigm life would be alot easier :)

Post new comment

Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Sort A-Z