Using Web Forms in an MVC Site

I’m teaching an HTML5 course this week, but one of my students had an ASP.NET question: how do you combine Web Form pages with ASP.NET MVC? It’s an interesting question, and not one that’s covered in any of our courses. Our MVC class covers MVC, our Web Form course covers Web Forms… and never the twain shall meet. But actually, combining the two is very straightforward, and can be very useful. ASP.NET MVC is great… but it doesn’t do grids anywhere near as easily or as well as Web Forms. And what if you have legacy Web Form pages that you want to include in your shiny new MVC site so that you don’t have to recreate absolutely everything on day one?

Here’s how you do it.

First, let’s build an MVC site. I created a standard MVC 4 site:

Using the Internet Application template and Razor syntax:

That gives a basic structure and sample controllers/views:

Now I want to add a nice grid to display a list of restaurants. I could do this the hard way with MVC, but why bother when I could use the Web Forms GridView?

So first I create a quick Entity Framework .edmx file for the table I want to display:

Then I add a Web Form to my site. That’s easy. Just right-click on the project and use Add | New Item….

Then I drag on a GridView…

And configure it to use an Entity Data Source pointed at the Restaurants entities, with some auto format goodness to make it purdy…

Then I add a link inside the layout view that points at my .aspx page (so NOT an MVC style route):

And when I click on it – tara! – I have a working Web Form page with a Grid inside an MVC application:

There is, of course, a catch. You can get some issues mixing the two forms of routing together (MVC logical routes and Web Form end points). The solution here is to tell MVC to ignore incoming routes that contain .aspx. You do this inside the RouteConfig in the App_Start folder:

And now we have an application that uses both ASP.NET technologies.

Of course, in the real world you’d have to worry about making your Web Forms look and feel like your MVC site, and there’s the whole thorny issue of keeping them in sync and how you can have a well-organized site with two different approaches to the UI…. But on the other hand, it’s nice to be able to take advantage of Web Forms where they can do things easily, and it makes migration from Web Forms to MVC much easier.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building ASP.NET Web Applications: Hands-On

Building Web Applications with ASP.NET MVC

Type to search

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.