Developer

First impressions of ASP.NET's MVC framework

Find out why you may want to use Microsoft's Model View Controller (MVC) framework instead of Web Forms.

ASP.NET development's presentation layer has traditionally been difficult; simply put, it isn't simple. The event model, for example, can confound even the most experienced developers. For someone transitioning to ASP.NET from a system such as PHP or HTML, the idea of coding to respond to a button click instead of a form posting can be odd. And, of course, the View State has always had major drawbacks.

To address these issues, Microsoft has been working on an alternative for Web Forms called the MVC framework. On September 10, 2008, I attended a seminar presented by Brian Hitney of Microsoft at the Columbia Enterprise Developers Guild meeting. Brian did a good job explaining what the MVC framework is and why a developer would use it instead of Web Forms.

Model View Controller

If the letters MVC sound familiar to you, it's because they stand for Model View Controller, a design pattern that has been around the industry for quite a while now. In this case, the MVC system bakes into ASP.NET a lot of things that developers frequently hand code into their applications to simplify development. For example, many developers end up rewriting something similar to Apache's mod_rewrite system in order to provide REST-friendly (heck, simply "friendly") URLs; MVC works this way as a rule. It also eliminates the code behind system, although you can still use master pages.

MVC breaks up the responsibility of responding to a user request into three functions: the model, the view, and the controller. In this case, the model is the underlying business logic, the view is what generates the HTML, and the controller determines what actions to perform. All of the application's business logic gets put into the model in a structure that you feel comfortable with.

By default, MVC provides what amounts to a small domain specific language (DSL) similar to a networking device's rules list, a system called URL Routing; this is used within the Global.asax file to translate URLs into controller actions. It is possible to replace this with a system of your choice, but the system that Brian demonstrated seemed more than capable for all but the most complex Web sites. It was also clear that if it was preferred to store these rules in a different format or outside of Global.asax, it was entirely possible to put them into an XML file, a database, or wherever you pleased, and simply put code into Global.asax to parse that and load the rules into the URL Routing engine. Once the URL Routing system determines the correct controller to use, it calls the controller and passes on the request data in a format defined by the URL Router's rules. The controller takes the user's input, decides which calls to the model are needed, and makes them, passing along the needed input. It is recommended that the typical controller not be more than a few lines of code.

The view is not supposed to know about any of the underlying details or data structures; it's role is to transform the data provided into HTML output. You can use any view engine you want, but MVC ships using ASP Web Forms as the view. But MVC doesn't use Web Forms, right? Yes, but it is still using the ASP.NET Web Forms parsing of the .aspx files by default. As a result, the views are .aspx files with HTML blended with traditional <% %> and <%= %> tags to produce the output. The transformation of data from the model into HTML is generally handled either by code in the view to generate the HTML, the slipstreaming of pieces of data into hardcoded HTML, or the use of helper functions, which get passed the data and create the appropriate tags with the requested options. This gives the developer ultimate control over the HTML produced, which is a major weak point of the Web Forms system.

How MVC stacks up against Web forms

Some of the advantages that Brian showed MVC to have over Web Forms during his presentation include the following:

  • It's possible to run unit tests on the entire output.
  • MVC is more easily maintained and changed.
  • MVC has cleaner URLs and HTML, which is good for SEO purposes and providing REST APIs.
  • MVC provides 100% control over the HTML output.
  • MVC eliminates View State.
  • MVC streamlines the development process due to the separation of concerns.
  • MVC allows you to "manage for change."

A major drawback

I feel like the view is where the biggest problems in MVC reside. The code looks an awful lot like the classic ASP pages that developers were glad to escape. On top of that, a great many ASP.NET developers simply do not know HTML very well because the Web Controls handled that for them. This means that a shift to MVC would require them to bone up on HTML and CSS. Also, because you lose the Web Controls, you also lose ASP.NET's AJAX functionality. In other words, you are giving up a lot of the power of ASP.NET in exchange for a better way of writing applications.

A hard sell to management

I grilled Brian pretty hard during the Q&A portion of his talk. Overall, I liked his answers, but I felt that it would be hard to make a business case for MVC, unless you have a boss that lets you make decisions at this level. Frankly, few development managers that I know would be thrilled about having an application written in a system that is radically different from "the norm" and MVC certainly fits that criteria. The big stumbling point from a technical angle is the decision to retain the ASP.NET engine by default for the view system. I can understand the decision -- it lets Microsoft ship the product a lot earlier and preserves existing knowledge -- but I still think that it is a mistake.

A fellow developer's endorsement

I spoke with Chance Dinkins, the owner of and lead developer at Mortal Creations, a Columbia-based Web development company. He has been using MVC since its first release about eight months ago and much of my initial interest in MVC came from him. He gave MVC the following endorsement:

"In my opinion, the MVC framework is by far the cleanest and most productive line of thought that has been built into the ASP.NET platform. It provides a level of control that often leaves developers wanting under Web Forms. Ironically, this is probably the biggest obstacle that it faces when trying to attract existing ASP.NET developers currently using Web Forms because the tradeoff is the removal of drag-and-drop programming. For this reason, it will not suit everyone and the devs working on the project have stressed this. If you like the idea of separation of concerns, test driven development (TDD), complete control over the framework and your output, and the removal of hacks such as View State, then you will absolutely love MVC."

A welcome alternative

MVC is a welcome change of thinking for ASP.NET. Developers from other platforms, particularly PHP and Ruby on Rails, are probably chuckling to themselves right now, since they have had something like this for years, but for developers wedded to the .NET platform, it is a welcome alternative.

MVC is currently in its fifth CTP, and the next release will be a public beta. It is expected to eventually be folded into the .NET Framework, so you can expect that if you learn MVC today, it will have widespread support in the future. The healthy ecosystem around MVC is already growing.

J.Ja

Disclosure of Justin's industry affiliations: Justin James has a working arrangement with Microsoft to write an article for MSDN Magazine. He also has a contract with Spiceworks to write product buying guides.

----------------------------------------------------------------------------------------------------------------

Get weekly development tips in your inbox Keep your developer skills sharp by signing up for TechRepublic's free Web Developer newsletter, delivered each Tuesday. Automatically subscribe today!

About

Justin James is the Lead Architect for Conigent.

19 comments
Mark Miller
Mark Miller

I forgot to ask this. You said that the MVC framework doesn't use viewstate, and that you can't use Web Controls. So I guess you just use standard HTML/CSS. Is there any mechanism provided for persisting control state, or do controls have to be refreshed by the app. when the page is?

Mark Miller
Mark Miller

In a .Net project I worked on some years ago I wrote my own version of Document-View for it because I was creating a screen that was too complex to be comfortably dealt with in normal Web Forms fashion. It was like Document-View in MFC. All view and controller code was in the web form, but all business logic was in a series of "documents" (collections of business objects). I was able to use drag-and-drop controls and manipulate a normal .aspx page. Just separating the business logic out into objects was a big win. I had worked on a similar screen before that, and I just used the architecture Web Forms gave me. It was terrible! The scheme I came up with felt familiar because I had worked in MFC prior to getting that job. I probably would've liked more of a separation of concerns than what I had. I would imagine losing ASP.Net's AJAX functionality would be the biggest loss. AJAX is a hack as it is. It's much nicer to have a framework handle that ugliness for you.

abibaby
abibaby

Lets say you have a typical CRUD page, with search, select to edit and stuff. When i entered a keyword, selected some category options, date range & stuff, went to page 3. Selected edit. Did my edit, when i am done, i will be thrown back to search page with no options. So this mean i need to start storing all the data in Session. This means, i can't have multiple windows open to work. Wish there was a concept of SemiViewState, to store these values. May be group a set of pages, provide a Key. That key gets passed around in urls.

Saurondor
Saurondor

Justin, how does this stack up to open source solutions like Spring? I use Spring MVC instead of Struts or JSF. There is a Spring port for .NET. Although I don't use .NET I would expect Spring to behave in a similar fashion. Any feedback on this?

david.cuthill
david.cuthill

Credibility blown on the first punctuation mistake.

Justin James
Justin James

Does this look like something you would prefer over Web Forms? Or does it seems like more work to learn and see where it fits in with your environment than it is worth? J.Ja

Justin James
Justin James

Mark - Correct assumption, it is up to you to persist state, if you choose to have that done. Since MVC is based on the idea that every action accesses a different resource, this makes sense. for example, "Edit" is a different resource than "View", even if the end result is to produce HTML output that looks quite similar; in Web Forms, you'd just toggle the "Enabled" property of the controls (as an example). One thing that some of the folks I've talked to have said, is that many people end up taking a "blended" approach, where portions of the application that benefit from the traditional Web Forms model use it. This is especially common when trying to introduce MVC into an existing application/site. J.Ja

Justin James
Justin James

Yeah, I've seen quite a number of systems that end up implementing something similar to MVC too. It looks like they either poor a ton of effort into it, or they put something together that doesn't work terribly well. I am sure that people looking to work in that fashion would be happier to use this framework than to cobble their own together. :) J.Ja

Justin James
Justin James

I agree, that is (and always has been) a tough problem to solve. One of the hardest challenges that is common in Web Development is simply coping with "Open in new window/tab"! One approach that you seem to be considering, is for the search screen to have an "origin key" variable added to the URLs on the page, so that any pages branched from there that may need to return the user to the origin can do so; a simple lookup table of URLs to a key should do the trick. A lot of sites use that, and it is a fine method to use. J.Ja

Justin James
Justin James

I really can't compare to Spring, Struts, or JSF, since I am extremely unfamiliar with those technologies. I *beleive* from what I have read, that JSF (assuming you mean "Java Server Faces") is more comparable to "Web Parts" in ASP.Net than ASP.Net MVC. Hope this helps! J.Ja

gormark
gormark

Are you capable of putting together a simple, coherent sentence? Your ridiculous comment contains more grammatical inaccuracies than the entire article you're commenting on. Get that thumb out of your mouth and use it to flip a few pages of an elementary school book for a change.

djustus
djustus

I would rather read a technical article written by a IT person than one written by an English major. Please read the content, not the punctuation.

Justin James
Justin James

First, what punctuation mistake are you referring to? I did not see any in the first paragraph. This piece was not only double checked by myself (not to mention Word's checker), but by a professional editor. I am not saying that we are infallible, but I would like to know where the mistake was made so that it can be corrected. Second of all, to say that "credibility was blown" is absolutely rediculous. Even some of the most professional pieces of content have the occassional grammar or spelling mistake. If you are truly someone who says "this has no credibility" because of a minor punctuation mark problem (note that I am a programmer, not a novelist), then you are probably only able to read The New Yorker and The Economist (note: I know that their names should be italicized, but I never figured out how to do that in this editor). J.Ja

howkuang_par
howkuang_par

Hi, I have been hearing MVC for some time and I have not really gone into learning the framework. Please excuse me if I made any mistake about MVC. I have been practising View-Presenter and Dependency Injection for all my web application and I was once thought MVC is very similar. But after reading this, I wonder how to convert from an existing ASP.Net web appliation to MVC pattern? Futhermore, does MVC flexible enough to support up to .Net 3.5 (Im more worried in View layer). Please advise. I believe I will try it with a new project instead of an existing one.

programmeroo
programmeroo

It seems that major changes in the VS design tool would only be done to accomodate a new UI or browser interface. It doesn't make sense to create a new tool to do the same thing. Perhaps Microsoft is getting ready for something fundamentally new. Okay, that was wishful thinking... I enjoy your articles Justin. You do a fine job.

Saurondor
Saurondor

Yes Web Parts is more comparable to JSF. Down to the buttons in HTML being linked to methods to be run once clicked and the bean mapping to HTML that JSF handles so well. Unfortunately it is extremely heavy and Springs simply beats it hands down. It takes a bit more coding on the XML config files, but it is worth it at test time. It is also less coupled to the HTML part of the project. We've had bad experiences with very good visual design tools that end up being to tightly bound. Ended up limiting our flexibility and how we could alter the behavior of components or introduce other frameworks (like security and authentication). Our switch has lead to more flexibility and smaller project footprints.

DukeCylk
DukeCylk

You do a bang up job here, and no one's asking for perfection here...I have taken opposition a few times in here, as this is merely a forum...a place to intiate conversation...not unilateral termination by snobbery....note, I paid very little attention to my grammar or credibilty, and though I was an English major at one time, I learned I could make a lot more money as a hack of a programmer cause there were far too many IT snobs lauding over their mainframe empires back in the 80's unwilling to share knowledge...maybe cause they were insecure and afraid of being recognzed as frauds, like this guy

Justin James
Justin James

MVC will work with .Net 3.5. In terms of converting an existing project, I would suggest a hybrid or blended approach, where you put in the URL router to pick up any requests that do not already have pages created, and then develop new functionality in MVC where is makes sense to do so. Trying to convert existing pages to MVC will be a really big headache, unless they are very simple. Hope this helps! J.Ja

Justin James
Justin James

First, thanks for the kind words! In terms of the designer... with the current default presentation layer being the standard ASP.Net system, the Visual Studio designer works fine on it. If you design to use a different view system, some of them may hook into Visual Studio to provide a designer, some don't. Either way, you lose the standard Web Controls. I would imagine that Expression Web would do a fine job editing the page as well, and it is a product that I rather like. Personally, I wouldn't mind the ASP.Net system as the presentation layer, if it did not look so much like classic ASP; in and of itself, that's not the *worst* thing in the world, but it does have a tendency to "break" designers when you do something like: Contents: It really gets ugly quickly, and these are the exact scenarios that the standard Web Controls handle very well while still not breaking the designer. J.Ja

Editor's Picks