Dave Paquette

Caffeine Driven Development

So you inherited an ASP.NET Web Forms application

December 30, 2013

ASP.NET MVC has been around for a while now, so there is probably a good number of us who have only worked with MVC apps. Maybe you are one of those people and you have never touched a Web Forms app. You probably know what Web Forms is, but you have never actually worked on a large scale Web Forms project. Then one day, you start a new job. You open up that solution file on your first day and it hits you: BOOM! You’re now leading a team working on a big old messy Web Forms project.

Stay Calm

Take a deep breath and resist the urge to re-write the entire application in MVC. Why? Just for a refresher, read Joel Spolsky’s classic article: Things you should never do, Part 1. I still think there are some extreme cases where a re-write is the best option, but 98.3% of the time a re-write is a huge mistake.

Believe it or not, you are not alone in this whole Web Forms thing. The number of Web Forms projects in the wild still vastly outnumbers the number of MVC applications in the wild. And just because it’s a Web Forms project today, that doesn’t mean you can’t start using MVC for new features.

MVC and Web Forms in the same project?

That seems messy. Should we really promote such madness? Well, if you create a new Web project in Visual Studio 2013, you will notice that you no longer make the Web Forms vs MVC choice up front. There is now only 1 option, and that is ASP.NET Web Application.

image

Once you click OK, you are then prompted with an options dialog where you can in fact choose to create a project that contains both MVC and Web Forms.

image

This is part of the One ASP.NET concept that the ASP.NET team has been talking about for a while now. The message from the ASP.NET team is to stop thinking about it as ASP.NET Web Forms vs ASP.NET MVC vs ASP.NET Web API. Let’s just call it all ASP.NET and inside our ASP.NET projects we can include whatever pieces of ASP.NET we want to use.

Personally, I like this idea, because it makes me feel a lot better about that Web Forms ASP.NET project I just inherited.

Catching up with the rest of the world

Here are some relatively easy steps you can follow to get your project to the point where you can start leveraging some of the newer ASP.NET technology like MVC and Web API.

1. Upgrade to latest version of Visual Studio

Update to the latest version of Visual Studio that is available to you. As of writing this blog post, the latest version is 2013. Upgrading is usually straightforward. Simply open the solution in the latest version of Visual Studio and follow the steps in the Upgrade Wizard. You might need to upgrade some 3rd part components as part of this process. For example, if you are using Crystal Reports, you will need to install the latest Crystal Reports for Visual Studio.

2. Convert from Web Site Project to Web Application Project

If your application has its roots in a much older version of Visual Studio, you may be dealing with a Web Site Project. You can tell you are dealing with a Web Site Project by selecting the project and checking if a WEBSITE menu item appears on the Visual Studio menu. If so, I would strongly recommend you convert to a Web Application Project before proceeding to the next step. Follow these steps on MSDN.

3. Update all projects to the latest version of .NET

Right click on the Web Application project and click on Properties. Change the Target Framework to the latest version of .NET. Do this for each project in your solution.

image

 

4. Add MVC

This is traditionally a step that was very manual and rather clumsy (see here and here). Now thanks to Nuget and updates to Visual Studio, we can do this with very minimal manual changes to our application.

Start by adding the ASP.NET MVC libraries using Nuget. Right click on the Web Application Project and select Manage Nuget Packages. Select the Online option on the left and search for ASP.NET MVC. Click Install.

image

Alternatively, open the Package Manager Console and enter the following command:

Install-Package Microsoft.AspNet.MVC

In previous versions of Visual Studio, you needed to add a special Project Type GUID to the project file before Visual Studio would allow you to add MVC Controllers and Areas to the project. If you are using Visual Studio 2013 or Visual Studio 2012 Update 4, then this is no longer necessary.

To get started with MVC in an existing Web Forms application, I strongly recommend using an MVC Area . This will help by keeping the controllers, models and views in a separate folder and also isolate changes to your web.config. To add an Area, right click on your web application project and select Add –> Area.

image

Give your area a Name, and Visual Studio will add an Areas folder containing a subfolder with the name you specified for your area. The subfolder will contain 3 sub-folders: Controllers, Models, and Views. You will notice a web.config file under the Views folder. This contains the configuration necessary for the MVC View engine and keeps us from needing to change the root application’s web.config.

Now you can add a Controller by right clicking the Controllers and selecting Add –> Controller. Select the empty template and provide a name for your controller.

Right click the return View(); section of the generated Index controller method and select Add View.

image

You now have a fully functioning MVC area in your existing Web Forms application. The last step is to add some startup logic to ensure that MVC area is properly registered. In the Application_Startup method of your Global.asax file, add the following line:

AreaRegistration.RegisterAllAreas();
AreaRegistration.RegisterAllAreas();

 

Now run the application and navigate to your new MVC view by adding AreaName/ControllerName/Index to the end of the root URL for your application. Both your old Web Forms pages and your new MVC views should work. Magic!

image

 

This represents the absolute minimum amount of change needed in your Web Forms application before you can start using the latest version of MVC (or Web API). To start using more advanced MVC features you will also need to configure Routing, Bundling and Filtering.

26 thoughts on “So you inherited an ASP.NET Web Forms application

  1. Pingback: Dew Drop – January 2, 2014 (#1693) | Morning Dew

  2. Rob says:

    This is a great article. I would have loved it if it were targeting those of us still writing web forms apps simply because the latest architecture is such a moving target we can’t tell which technologies have already come and gone since web forms, and what is actually the go-forward stack. Instead, the article makes us feel like dinosaurs :)

    • My apologies, it was not my intention to make you feel like a dinosaur :)

      I was simply writing this from my own perspective of not having worked on any large Web Forms projects. While you were doing Web Forms, I was doing Delphi, then Win Forms and WPF. We are both dinosaurs that came from different places :-)

      • Ian Yates says:

        @Dave Paquette – same!
        We’ve jumped head first into MVC and now JavaScript (and its many [pick any noun] frameworks) + WebAPI. Delphi served us well for years but C# is just sooooo much more productive. I also skipped WinForms myself although I did dabble in WPF for a bit.
        I’m investigating TypeScript & KnockOut so I can still have the compiler catch the obvious bugs for me whilst still getting the goodness of binding :)

  3. Great article and problem I’ve faced quite a few times. Our team went even farther with our integration between the two. Rather than just using the two platforms side by side, we started to implement MVC patterns in the legacy WebForms pages that were directly transferable between the two.

    We rewrote all master pages within a legacy application to render partial views for the header and footer layouts. The WebFormMvcUtil class found here was invaluable: http://stackoverflow.com/questions/702746/how-to-include-a-partial-view-inside-a-webform

    That way we only had our layout in our partial views, but they were being used across both MVC and WebForms apps.

    Then we created a generic view models which were used in both the controllers and the WebForms pages. This allowed us to share models between the two platforms and ease the transition to converting WebForms pages to pure MVC.

    It was a long (but fun) learning experience getting the two to play nice, but the result was worth it.

  4. Pingback: So you inherited an ASP.NET Web Forms application | StupidPC.com

  5. Dominic says:

    Thank for sharing.Learn a newthing in a new year.

  6. NicoPaez says:

    Hi,

    I am in a situation like this. A webform app and now the client wants to apply a new weird design based on html5 and css to a couple of pages. Adjusting the webforms to the new design could be really hard, so I am considering implement this new pages with MVC.
    I will try to follow your recommendations, but I was planning to use VS2012, should I use VS2013 instead?

    Thanks!
    NicoPaez

  7. Mike says:

    The 100 % rewrite may not be necessary, but sometimes it is worth the effort. I have rewritten a few web forms projects that where huge and complicated. I remade each one in MVC in only a few days with far less coding than the original web forms projects. In the end, I ended up with a much nicer looking project that functioned much better. I found mistakes and bugs in the web forms projects that were not noticed until the rewrite. Both methods can be beneficial depending on the nature of the project.

    • Stacy says:

      I agree and I’m doing a rewrite now from webforms to WebApI/NancyFX, Angularjs, queues, events. Trying to retro-fit felt like putting lipstick on a pig, for my use cases.

    • I suppose I should clarify. When I saw that a rewrite is usually a mistake, I am referring to systems of substantial size. If a system can be rewritten in less than a week, then I would consider the system to be relatively small.

  8. Raju Golla says:

    Adding a MVC project team is trivial.

    Is the events and application/page life cycle between these two models support best integration?

    In other words ‘Is it feasible to communicate between these models by taking the life cycle etc. reservations?

    Thanks,
    Raju

  9. tim says:

    This is a great article, but I would like to propose that MVC is not the only way to go.

    If you have an old WebForms web site project where there is no solution/project the structure will actually be more similar to the new WebPages (WebMatrix) framework which also uses a file based system instead of a project based system.

    You might even be able to move your WebForms pages directly to cshtml pages with very little edits. WebPages allows you to control all your HTML just like MVC, but lacks things like unit testing and separation of concerns. In other words it is much less complex than MVC.

    This option could be attractive for web developers who do not want to learn MVC for some reason. It’s especially well suited if your site is an informational site. If your site has 10 aspx pages and a contact form it can be easily moved to WebPages. You do not need MVC for those types of sites. Even if your site is larger and has quite a lot of server side code WebPages has the full .net framework behind it just like WebForms and MVC so it can do anything they can.

    Going back even further, if your site is a PHP or Classic ASP site then WebPages was made for you to move to .net. It’s has a low entry barrier and very low learning curve.

    A benefit of going this route is that WebPages is more similar to MVC than WebForms is. You can start off by moving a small site to WebPages and if your site becomes more complex the WebPage Razor code can be more easily moved to MVC views.

    I understand this article is for moving large WebForm projects to MVC and for that MVC is probably better. If you have very large projects with complex business logic and multiple developers MVC is a great framework. However, most sites moving from WebForms to something else are probably small information sites. I just wanted to mention this alternative and hope people consider WebPages in cases where they do not need the benefits and added complexity of MVC.

  10. Charles says:

    Nice article.

    I have a very large WebForms (lol, Web Site Project) application that is a CMS/e-commerce system for multiple sites. All my HTML content, etc. is stored in a database, which is loaded with dynamic UserControls. All the functionality is encapsulated in these dynamically loaded User Controls.

    I can almost see how to convert a simple WebForms application to MVC (and I have created some from scratch), but not a multi-site CMS system. Orchard looks just over the top complicated as an example.

    Is there a simple MVC CMS sample? Also, what is the equivalent of a dynamically loaded UserControl in MVC?

    Thanks!

  11. Simon says:

    The equivalent to UserControls in MVC is a “PartialView”.

  12. Musa Vilakazi says:

    Hi all,
    thanks for this informative article and the different views in the comments.

    Although I do have some experience in the earlier versions of MVC, I still am not clear on the benefits of it as opposed to Webforms because in my limited view Webforms still allows me a lot more flexibility in the things that I want to do, so much so that I am reluctant to even look at MVC

    However I am aware that times are changing and the market is now demanding more of the new and for the sake of remaining relevant and flexible I have resolved to get into MVC. But now there are such things as Webpages-Razor. My point is that it is now challenging to decide on a way forward all these options are equally interesting, but what is important is relevance now and 2-5 years later.

    I guess what I am asking is, which is the way to go, which has a future or does one pick one way and really hope for the best???

    Any thought are welcomed?

    • Hi Musa,

      I cannot pretend to know which framework will be the most popular 5 years from now. My advice is to always be learning something new. My recommendation for you as an application developer in the ASP.NET world would be to learn more about MVC, Web API, SignalR and OWIN.

  13. Martijn van der Corput says:

    Nice article!

    I work on a Web Forms / MVC project on daily bases and we were also struggling with the question if we should replace all functionality in existing ASP.NET Web Forms pages to MVC views. Eventually we decided to create big new features in MVC, but we will still refactor and extend Web Forms functionality that is working the way it should. Why throw away something that is working?

    Combining Web Forms and MVC is very doable, and you could use the best of two!

  14. Dan says:

    First of all, thanks for the good article.

    I’ve been working on CMS and ERP systems for 10 years, starting with classic ASP, and now owning a big fat webforms system that I host to about 100 companies.

    So far, it’s pretty easy to manage, and the load really isn’t a problem (since it’s all internal company stuff, not public).

    I’ve been looking at MVC (of which I know almost nothing), and realize that I’ve got to keep my investment at the leading edge, but I don’t really see the cost/benefit working out.

    What exactly are the drawbacks of webforms that make people want to convert to MVC? Is it just speed and/manageability? Because our site is fast enough and pretty darn simple to manage. I don’t want to start working nights on a project unless I can justify the costs.

    Thanks for any advice and thanks for the good article.

  15. Jim says:

    Hi Dave,

    Great article! How does your implementation differ from adding an MVC scaffold to an existing Web Forms project? Is it better to install the MVC runtime package as you suggest or add a MVC scaffold to an existing Web Form project? Thanks.

  16. Gage says:

    This saved my ass today. I deployed a new MVC project to the root directory of a site (that was previously a WebForms site) with about 20 Web Forms applications as subdirectories. This post helped me update all the projects and get them back up and running. A big thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">

Current day month ye@r *