Skip to content

9 Steps to switch from ASP.NET Web Forms to MVC

July 10, 2012

MVC has been gaining lot of momentum in the community recently, but not everyone can move to MVC right away. This could be because of large applications, customer requirements, management decisions etc. This shouldn’t necessarily mean, you can’t take steps to get your code ready for an eventual switch to MVC.

Important Note: If you are an experience Web Forms developer, you may feel like some of the below suggestions may look some of these suggestions may look squeamish.

If you like Web Forms, by all means, continue using that model to its fullest extent and take advantage of all the features it has to offer.

However if you’re looking to make the switch then keep reading and see how many of these steps you can implement in your project.

Step 1: Move code out of code-behind files

The easiest step you can make towards weaning yourself off Web Forms is to separate your Web-Forms-specific code from your general business rules, logic, data access, etc.

If you find any of this code lying around in your code-behind files you should move this to a generic class that can be re-used anywhere. Make sure this generic code does not reference things like the Request or Response object (you should still access these from within your Web Forms code-behind).

If you’re not sure where to put this code you can create a static class somewhere and organize it as you go. You can also move your code to a separate class library DLL to help keep things organized.

Step 2: Stop Using ViewState

Despite what you may have heard in the past there are no situations which *require* you to use ViewState in a Web Forms app. That’s right: zero.

Even for times when you want to re-display data that a user entered into a form between post-backs there is no need for ViewState; that data is already in the Request.Form collection. Controls like asp:textbox can read their previous values just fine without ViewState (try it!).

You might find that there are cases where you use ViewState to store data that was fetched from the server during the initial “non-postback”rendering. In general I would say that this is a bad practice. The user’s browser shouldn’t be used to cache data needed by the web server. Any time you see code like this:

Image1

You can simply replace it with this:

Image2

Step 3: Stop Using Post-Back

Let’s be clear: posting an actual form to the server is perfectly fine, however you should generally avoid using the HTTP POST method in most other circumstances.

Most often post-back is abused in order to change the output of a webpage based on user interaction. If you look in your code-behind and see events wired up for things besides a form’s “submit button click” then you should start cleaning this up by differing your output based on querystring instead of by post-back events.

Step 4: Ditch the Global Form Tag

Now that you’ve weaned yourself off of ViewState and post-back it should be relatively easy to remove the <form runat=”server”>tag from your master pages. It isn’t required if you aren’t taking advantage of ViewState.

Step 5: Centralize Your Code

You’re asked to investigate why certain data is being displayed on a specific page in your app. Where do you look to find out where the data is being fetched? The code-behind of the aspx file? The front-end? The code-behind for a control on the page? The ascx file? How about the master page code-behind? Master page front-end? HTTP module? Global.asax?

Projects can get messy, and while MVC isn’t a cure-all it does do a much better job of coaxing people to put all of their “fetch” code in controllers, while the views stay “dumb” and merely read the results of the controller’s processing.

There’s no reason you couldn’t start organizing your code like this in a Web Forms project, too.

Avoid making controls that go out and fetch their own data, and instead try to do processing in the code-behind for your aspx file and pass that data along to any controls that would need it.

Don’t let your aspx or ascx files make direct calls to functions themselves, keep this in the code-behind and bind the result or expose the result via properties (see the next step for more on this).

Try to keep your master pages light and don’t treat them as a pseudo base-class for your files (they aren’t).

Not only will your project be closer to the MVC model, but you’ll have a much easier time debugging issues when you know that you can always look in the code-behind of the aspx file (or perhaps one of its base classes) rather than hunting down the offending code all over the project.

Step 6: Stop Using Controls

Now that you aren’t using ViewState or post-back and you’ve got all of your processing logic in your aspx code behind, you could question why you should continue to use ASP.NET controls at all.

This will make some experienced Web Forms developers feel uncomfortable because they’ve been taught for so long that the main distinction between platforms like ASP.NET and “lesser” frameworks like PHP or classic ASP is that ASP.NET controls allow for a separation between server code and HTML rendering.

But you don’t need to use controls in order to separate rendering logic from server-side code. We can continue to use the code-behind to invoke all of our data access code or business rules code (which should be in separate classes by now), as well as to access the request/response objects as necessary.

All the front-end really needs are properties to be exposed by the code-behind which give us the result of these operations. Read-only access, in other words.

Step 7: Use Models

Now that you’ve got your master pages setting properties to be read by the front-end code, why not store all of these properties into a single “Model” property? It was a good idea for MVC, and it’s a good idea for Web Forms, too.

Instead of writing code like <%= this.WidgetName %> or simply <%= WidgetName %> you could write <%= Model.WidgetName %>.

This would force you to create model objects for each of your unique views just like MVC, which you could re-use as you convert your project. If you choose to go this route you can also put your models in a folder called “Models” ahead of time for consistency with MVC best practices.

Step 8: Route Your aspx Pages

ASP.NET 3.5 introduced routing for Web Forms pages, and 4.0 made it even easier to use.

In .net 4.0 you can add code to your global.asax to specify the route. Then you can retrieve route parameters in the code-behind by using RouteData.Values collection.

I also recommend keeping all of your routed pages in a special directory like “Views” with it’s own web.config. You can add entries to the web.config in this directory to prevent direct access to these pages:

Step 9: Add MVC into your Web Forms Project

You might think we’ve practically turned our Web Forms app into MVC-lite at this point, but we’re not done yet: let’s just add the real thing!

That’s right: you can add MVC code directly into your existing Web Forms project and run them side-by-side in the same project. They can use the same DLLs, the same session, same authentication, etc. No virtual directories are needed, either.

If you’re thinking to yourself “I bet this process is completely automated, painless and well-documented”, then you haven’t been a .NET developer for very long, have you? 🙂

Final Thoughts

I expect that as you read this there are product managers around the globe who are not comfortable enough to convert their half-a-million lines of code Web Forms site into MVC overnight and I couldn’t blame them.

However, if a conversion to MVC is a future goal then I would suggest following as many of these steps as you can (or feel comfortable with) now in order to make that conversion less painful.

If you feel that parts of your site can be converted more easily, or if you’re creating brand new sections which are somewhat isolated from the rest of the project, then go ahead and add MVC to your site and see if you can get the new pages running in MVC side-by-side with the Web Forms pages.

Keep in mind that you won’t get to re-use your master pages, so this could be problematic depending on how eager you are to duplicate template code between MVC and Web Forms. If things look too ugly then you might be better served by waiting for a full all-or-nothing conversion, possibly after a little bit of prep work to get the Web Forms code more aligned with the eventual MVC code.

From → ASP.NET, IIS, Web Apps

Leave a Comment

Leave a comment