Mixing Web Forms and ASP.NET MVC

Just because you're using Web Forms, it doesn't mean that you are stuck in a technical time-warp. If you want to liven up a site with new features using Ajax and libraries such as jQuery, Bootstrap or Knockout.JS, then you can always integrate a Web API layer into a Web Forms application. Dino Esposito shows how to give your Web Forms application a new lease of life.

Mixing Web Forms and ASP.NET MVC

Last fall I gave a presentation at a conference about the realistic options you have today for building web sites on the Microsoft Web stack. In the workshop, I was saying that I genuinely see no issues in using Web Forms today. Like every other thing in this imperfect world, the Web Forms technology has pros and cons, but it just works so it’s more than OK to use it even though it’s a fifteen-year old technology.

The workshop generated a lot of traffic on social media in the successive weeks. To me, it means that, even today, a lot of people are happy to use Web Forms and many production web sites are running on top of Web Forms. However, the teams behind these Web sites are, reasonably, looking ahead and planning new features. In doing so, they run across some of the structural limitations of Web Forms and wonder how best to avoid them.

The issue that most often makes ASP.NET Web Forms feel outdated is the lack of an efficient way to expose HTTP endpoints so that they can be easily consumable by whatever JavaScript framework you want to use on the client side. This contrasts with ASP.NET MVC which is particularly well suited for exposing lean and mean HTTP endpoints that return JSON data to clients.

ASP.NET MVC, however, pushes a different programming paradigm. While this new MVC-based paradigm looks familiar and attractive to Web developers coming from a Java or PHP background, it feels weird and cumbersome to developers who grew up with Web Forms and server controls.

Hence the question: is it really safe to mix Web Forms and ASP.NET MVC in the same project?

Adding Features to an Existing Web Forms Site

When it came out, Web Forms was the right framework at the right time. It was enthusiastically employed to build the first generation of business Web sites after the Internet bubble. Up until five or six years ago it was still the primary option for the Microsoft stack. Then ASP.NET MVC came out and today solutions based on client-side JavaScript tricks and hacks are more fashionable.

For a new project, you can take your time and evaluate whether Web Forms or other frameworks are ideal for the skills and attitude of people in your team. But what if you’re just trying to improve an existing ASP.NET Web Forms applications? So often, you have no time and/or budget for a complete remake of the site and you just want to implement a slew of new features using Ajax and libraries such as jQuery, jQuery UI, Bootstrap or perhaps Knockout.JS or Breeze.

Can you do that on top of Web Forms? Can you just bring in some ASP.NET MVC features and leave the rest of the site as is?

The Real Problems of Web Forms

Let’s briefly recap the problems of Web Forms so that it’s clear which benefits an additional framework can bring in.

As weird as it may sound today, ASP.NET Web Forms was originally devised to shield developers from the actual structure of the HTML being sent to the browsers. As a developer, you had no control-and only a faint idea-of the ID used to name HTML elements. In these conditions, how could you arrange to replace a grid or a chunk of text with downloaded data? Microsoft addressed this, and other minor issues, as soon as they showed up. ASP.NET Web Forms 4 (released in 2010) made DOM manipulation easy and effective also in Web Forms.

But that was only the first half of the problem.

Before developers can get to manipulate the DOM dynamically, they have to collect data from some remote HTTP endpoint. In some cases, these endpoints are located on sites outside of your control, for example Flickr, Twitter or other business partners of yours. The URLs are known and constants. Using JSONP, or other tricks, you can make the calls you need quite nicely.

How can you easily expose, instead, your own endpoints from within a Web Forms applications?

The first option to consider is just having plain old ASPX pages that return JSON data: Another option is using a HTTP handler. Both options would work well for slightly different reasons, but both are quite impractical solutions. In particular, they force you to dirty your hands with JSON serialization and deserialization. In addition, the burden of URL routing is all on your shoulders.

For years, we have solved the problems of having HTTP endpoints consumable from within ASP.NET Web Forms pages by wrapping ASMX Web services and, better yet, WCF services in auto-generated JavaScript proxies. The solution worked and still works; except that it completely bypasses jQuery and its huge range of plugins.

The real problem that makes ASP.NET Web Forms feel outdated is lack of an efficient way to expose HTTP endpoints in a way that is easily consumable by whatever JavaScript framework you want to use on the client side.

Web API Maybe?

As of 2014, the official answer to this problem is using Web API, as explained in this article I wrote for Simple Talk about a year ago.

Integrating a Web API layer into a Web Forms application couldn’t be easier. You just plug in the Web API runtime, configure routing so that you decide exactly which URLs you want to support and start writing your controller classes in the App_Code folder. Web API follows nearly the same programming model as ASP.NET MVC and is really easy to learn. In the end, it’s just like writing controller classes equipped with public methods callable from JavaScript clients. Here’s a quick example:

Standing the default routing algorithm, to invoke the method you just need a URL-like /news/all.

It turns out that Web Forms, when extended with a Web API layer, solves all the problems you may find on the way to making your existing Web Forms application more interactive and rich with some cool jQuery and jQuery UI plugins.

Web Forms Mixed with ASP.NET MVC

Web API is a relatively recent addition to the panorama of Web frameworks on the ASP.NET stack. And, let’s say that, it is confusingly similar to ASP.NET MVC. Web API is just pushing a programming interface that seems a clone of ASP.NET MVC. However, it is completely separated from ASP.NET MVC. And, just because of this, it is completely separated from the ASP.NET runtime too.

ASP.NET Web Forms and ASP.NET MVC share the same runtime environment and requests are routed through exactly the same pipeline. It is even acceptable to say that ASP.NET MVC is just a global HTTP handler installed on the ASP.NET request pipeline. If the incoming request matches the URL requirements supported by the MVC handler then the request is routed to it; otherwise it is processed by the runtime as usual. “As usual” here means just as if it would go in a plain Web Forms application.

If you add a plain ASPX page to an ASP.NET MVC project, well, it just works like a charm without any changes to the configuration. If you invoke the ASPX page, the ASPX page is processed with viewstate and postbacks. If you invoke another URL mapped to a controller class, the related action method is run and results are served accordingly. The figure below shows that all passes through the URL Routing HTTP module that captures each and every request.

1946-277e13ab-cbb9-4a8c-9466-ed9e4b9eb64

Intrinsic objects such as Cache, Session, User and the like are the same, because the runtime environment is just the same.

Should you expect to run into debugging or performance problems if you mix Web Forms and ASP.NET MVC in the same project? As in the figure you have two separate areas within the runtime. Each request takes its own way and can be debugged and tracked as appropriate. As for performance, it can’t be denied that the ASP.NET runtime will load a few more assemblies if it has to serve two flavors of requests.

Is this a problem? Let’s see.

The URL Routing module is a standard part of ASP.NET since version 4.0 released back in 2010. It’s already there whether you use ASP.NET MVC or not. The extra load is limited to system.web.mvc and what’s required to use Razor. Whatever way you look at it, you are not going to experience performance hits-what’s added has a negligible mass.

What about deployment?

I admit that it could have been an issue until Visual Studio 2013. For a while, my favorite way of doing things has been creating an empty ASP.NET MVC project first and then bringing in all ASPX pages of the existing Web Forms project. I found it to be the fastest and most reliable way to mix things. In Visual Studio 2013, though, things are much easier. You can open an existing Web Forms project and then just choose to add a controller class.

1946-1-0f14e34a-5c08-4c47-8ab0-ed9db665b

When you do so, Visual Studio 2013 just adds the full set of dependencies for ASP.NET MVC and you’re up and running in a matter of seconds. Note that Visual Studio offers the same nice service also if you add a Web API controller to a Web Forms project.

Why Mix Web Forms and ASP.NET MVC?

So now with Visual Studio 2013 you can add Web API and ASP.NET MVC to an existing ASP.NET Web Forms project with a click or two. But should you? I see two main scenarios for wanting to mix Web Forms and ASP.NET MVC.

Here’s the first. You want to rewrite your web site with ASP.NET MVC but also need to proceed step by step because the site is large and your team doesn’t feel very confident about using the MVC paradigm after years of viewstate and server controls. So you take one module at a time and rewrite it from scratch using ASP.NET MVC concepts. This means writing controllers, Razor views and routes. It also means preparing CSS and script bundles and start getting familiar with frameworks such as Twitter Bootstrap and libraries like jQuery and Knockout. If you have plans for building pages that are particularly JavaScript-intensive then it could also mean getting familiar with AngularJS. As you take this route, you also expose pieces of logic to JavaScript clients via controllers.

The second scenario is when you just want to add some interaction to some of the existing pages. This mostly means calling jQuery or jQuery UI and download JSON data from your servers. Given this objective, ASP.NET MVC is definitely a possible solution. However, in this scenario I’d rather go for Web API instead of ASP.NET MVC. At the end of the day, the difference between Web API and ASP.NET MVC can be summarized in the three points:

  • ASP.NET MVC is bound to the same runtime as ASP.NET and has tight dependencies on IIS and the system.web assembly;
  • ASP.NET MVC includes support for HTML rendering;
  • Web API has been designed without dependencies on IIS and the system.web assembly and to be just the Web frontend of an API.

While Web API doesn’t prevent you from returning HTML within a call, it’s specifically designed to return plain data.

Furthermore, what kind of ASP.NET Web Forms application do you have? Is it a plain old Web Forms application full of ASPX pages based on server controls? Or is it just what the Visual Studio 2013 template passes off as Web Forms? If you create a new Web Forms project with Visual Studio 2013 you get a bunch of ASPX pages that are for the most part made of plain HTML and with a very limited use of server controls. If you use DIV and HTML5 elements, if you style mostly with CSS and have more and more of jQuery, well, why insisting on Web Forms? You’re may be far closer to ASP.NET MVC than you think.

The Bottom Line

I’ve been mixing Web Forms and ASP.NET MVC for years now and all always worked beautifully for me. Likewise the many other people doing the same that I hear from via direct contact and Google and other search engines. Web Forms and ASP.NET MVC together? Yes, you can.