Adding MVC to existing ASP.NET Web Forms

MVC and Web Forms can happily run parallel to each other in a .NET project thanks to Microsoft's efforts to unify the framework. So adding MVC to existing ASP.NET Web Form projects is a good way to progressively upgrade a site without doing a full re-write.

The upgrade process is incredibly easy too:

  • In the project right click
  • Select add New Scaffolded Item
  • Select MVC 5 Controller - Empty
  • Give the new controller a name

This will automatically add everything that a bare bones MVC project would have, including Content, Script, Bootstrap, the View folder structure and the required references.

Existing webforms will work as normal and the new MVC controller and routes will also work in the same site assuming there are no conflicts on the route paths. This would be unlikely if the Web Forms are still being served on the .aspx extension. An added bonus is that the MVC features can be used with Web Forms too.

Bundles

As mentioned in an earlier post Bundles can be used with WebForms in the same way they are used with MVC improving static content delivery.

Routing

The new RouteConfig file will have been added to the App_Start folder and in this there will be the default MVC controller route setup:

public class RouteConfig 
{
    public static void RegisterRoutes(RouteCollection routes) 
    {
        routes.MapRoute(
            name: "Default", 
            url: "{controller}/{action}/{id}", 
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Additional Web Form page routes can be specified which are slightly different from the usual MVC routes, this means that during a site upgrade you have consistant URL structures between MVC and Web Form pages if required:

routes.MapPageRoute("", "SalesReport/{locale}/{year}/{*queryvalues}", "~/sales.aspx");

The only other change required for Web Form routes is that a page may need to access route parameters differently than query string parameters.

This can be achieved using the Page route data collection as follows:

Page.RouteData.Values["id"]