Click here to monitor SSC
  • Av rating:
  • Total votes: 21
  • Total comments: 3
Dino Esposito

Mixing Web Forms and ASP.NET MVC

25 February 2014

Just because you're using Web Forms, it doesn't mean that you need be 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, or mix Web Forms with ASP.NET MVC. 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:

public class NewsController : ApiController
{
   [HttpGet]
   public IEnumerable<string> All()
   {
     // Your logic and return data
   }
}

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.

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.

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.

Dino Esposito

Author profile:

A long-time trainer and consultant, Dino is the author of many popular books for Microsoft Press for .NET developers.including “Architecting Mobile Solutions for the Enterprise“ and “Programming ASP.NET MVC” both for Microsoft Press. CTO of Crionet, a firm specializing in Web-based and mobile solutions for sport events across Europe (http://www.crionet.com), at the moment Dino is also technical evangelist for JetBrains, where he focuses on Android and Kotlin development, and member of the team that manages WURFL—the database of mobile devices used by organizations such as Google and Facebook. Follow Dino through his blog at http://software2cents.wordpress.com or at http://twitter.com/despos

Search for other articles by Dino Esposito

Rate this article:   Avg rating: from a total of 21 votes.


Poor

OK

Good

Great

Must read
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.


Subject: Excellent Article
Posted by: Anonymous (not signed in)
Posted on: Monday, March 03, 2014 at 4:46 AM
Message: Excellent article. Thank you for sharing.

Subject: A Poor Man's MVC
Posted by: TodConover (view profile)
Posted on: Wednesday, March 05, 2014 at 12:36 PM
Message: I came late to MVC, having been stuck using VS 2005, but the benefits of the model were immediately apparent, especially the ability to separate, completely, program logic from the UI. Not only does this compartmentalization aid simplicity, understanding, and ultimately development, but it allows using the logic portion in a non-UI setting - which is especially useful to drive regression testing. But I was still stuck with VS 2005. So I developed a scheme to use the underlying MVC model, without the supporting technology. In short, the result is a traditional web form application with a single ASPX with a single asp:Label tag. My "views" essentially build the required HTML for each page and push it out to the browser through that label. What comes back is consumed by my "controller" which in turn calls the required "model" and the cycle starts again. It works just fine and I never ever look at or think about HTML. The best part is the controller automatically records the data flowing in both directions so that the inbound data instantly becomes a test script, and the outbound data is the test result - thus supporting regression testing. The important part of MVC for me is the model it suggests, the technology is just detail. Your article is insightful because you're focusing our attention on what the technology does for us; sometimes that gets lost. Thanks,

Subject: MVC controller not found in Add new item
Posted by: gs (not signed in)
Posted on: Thursday, March 13, 2014 at 10:53 AM
Message: Thanks for this article. Now feel more confident that I can start using MVC in my webforms website.

I have VWD Express 2013 and MVC 5 installed though I do not see a option to add Controller when I do "Add new item" in my webforms website.

Any ideas?

 

Top Rated

Acceptance Testing with FitNesse: Multiplicities and Comparisons
 FitNesse is one of the most popular tools for unit testing since it is designed with a Wiki-style... Read more...

Acceptance Testing with FitNesse: Symbols, Variables and Code-behind Styles
 Although FitNesse can be used as a generic automated testing tool for both applications and databases,... Read more...

Acceptance Testing with FitNesse: Documentation and Infrastructure
 FitNesse is a popular general-purpose wiki-based framework for writing acceptance tests for software... Read more...

TortoiseSVN and Subversion Cookbook Part 11: Subversion and Oracle
 It is only recently that the tools have existed to make source-control easy for database developers.... Read more...

TortoiseSVN and Subversion Cookbook Part 10: Extending the reach of Subversion
 Subversion provides a good way of source-controlling a database, but many operations are best done from... Read more...

Most Viewed

A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Calling Cross Domain Web Services in AJAX
 The latest craze for mashups involves making cross-domain calls to Web Services from APIs made publicly... Read more...

Web Parts in ASP.NET 2.0
 Most Web Parts implementations allow users to create a single portal page where they can personalize... Read more...

Why Join

Over 400,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.