Sunday, April 5, 2009

5 reasons why you should use ASP.NET MVC

I’ll be fair with you readers. I’ve only toyed with the ASP.NET MVC framework. It looks great as of now but it’s the first full blown MVC framework that we have that is backed by Microsoft. However, there is a lot of opposition nowadays that tend to be formulated like this:

Why should I use ASP.NET MVC? WebForms works well.

Other problems come from the lack of server controls. When a developer look at that and he then wonder why he should have to write HTML and Javascript when before he could have retrieved all that beautiful information with a simple postback.

So without ranting any further, here is 5 reasons why you should use ASP.NET MVC.

1. Testability

When the MVC model is properly applied, it allow for a better separation of your business logic and your presentation code. If the view is not included inside your model, you can easily test without requiring a web server. By default, when starting a new MVC project, Visual Studio offer to create a new Unit Test project based on Microsoft’s Unit Test framework. Other Unit tests framework can also be configured to be used by default instead of Microsoft’s solution.

The way the code is also made, the controller is the one handling the calls from the route. They can be instantiated outside of a web request which makes them easy to test too.

2. Perfect control of the URLs

ASP.NET MVC use URL Routing to better control the request and forward them to your controllers. Instead of 1 to 1 mapping, they allow pattern matching. The default being “{controller}/{action}/{id}” with the default being “Home/Index”. This technically allow you to set the URLs exactly how you want. You don’t have to create folder for every level deep it goes. The URL routing allows you to make clean URL that will be easy to remember.

Would you rather try to remember http://localhost/Sales/DisplayProduct.aspx?ProductID=23213 or http://localhost/Product/Detail/23213 ? Even better, if you are an e-Commerce site and want some fast link…. you can directly bind those URL to http://localhost/23213 to make it more easy to remember. Doing that in WebForm while keeping all this unit testable would just be too time consuming now is it?

3. Better Mobility Support

In WebForm, you would have to detect on each page that the browser is a mobile and adapt your rendering for the mobile on each and every form. You could also redirect the user to different page when it’s a mobile. What is excellent with MVC is that it’s not the view that is receiving the request. It’s the controller. The controller can then dynamically decide which view to render while keeping the same URL. So to see a product view, you don’t even need to send different URL to different provider. You just detect which device you are handling and redirect it to the proper view. As you support more and more mobile device, you can keep on adding view that are more specific to each device. Want to support this new HTC? Create a view, detect the browser and ensure the right view is displayed. Want to support some iPhone goodness with some device specific HTML? Create the necessary view, reuse the browser detection and display the view.

You can keep on doing that ad infinitum and as much as you want depending on your audience. Having Mobile support now is more convenient than it has ever been.

4. View Engines

Now if you only built ASP.NET WebForms, this term might be weird for you. Let’s just say that you have been using the same view engine all this time without wondering if you could choose. The WebForm view engine is… well… what you have been using all this time. This includes server tags (<% %>), binding tags (<%# %>) as well as control tag (<asp:TextBox … />).

The Spark Engine is a good example. MvcContrib also offer 4 different view engine (Brail, NHaml, NVelocity, XSLT). Each of those engine are created to fix some specific problems. Different view engines can be used on different view. One page could be handled with WebForm view engine, one with Spark Engine, one with XSLT, etc. Different view, different problem different solution.

You might not have to use those, but the simple fact that they are available will make your life easier if they are needed.

5. Built-in and shipped jQuery support

Let’s keep the best for the end. jQuery is shipped with any new project instance of ASP.NET MVC. Since Microsoft announced support for jQuery, it’s been the big buzz in the javascript world. Since ASP.NET MVC don’t rely on Postback, a strong javascript framework is needed to provide for all the UI the previous server control were offering. jQuery easily offer you AJAX, DOM manipulation, event binding and  this across browser.

Of course, jQuery is not an advance to MVC itself. But it is a serious offering from ASP.NET MVC. No more download or “I’ll write my own” stuff. I don’t know for all of you but if I have to do javascript, I normally do a document.getElementById. This will work in most browsers but as soon as you start going funky, some browser will misbehave. jQuery simply allow you to write $(“#myControlId”) or many more shortcuts to simply do what you need across browsers. Just by having jQuery available stops me from writing incompatible code.

Conclusions

Lots of point goes toward MVC. Way more could be added. You certainly don’t want to miss Kazi Manzur Rashid’s blog about ASP.NET MVC Best Practices (part 1, part 2). Scott Hanselman, Phil Haack also have great posts about ASP.NET MVC.

Don’t be fooled. Web Forms are not necessarly evil. They just aren’t leading you to a pit of success.

Submit this story to DotNetKicks

11 comments:

  1. Maxime,

    It it actually possible to use Webform controls with the MVC framework. I've heard success varies depending on how tightly bound controls are to the Postback/ViewState models.

    A demonstration of using WebForm controls with ViewPages can be found here: http://tinyurl.com/aspnetmvcdemo

    Cody Skidmore

    ReplyDelete
  2. Nice listing but make sure that you give credit where credit is due.

    1) Testibility - Given that you actually use WinForms correctly, you can get the same amount of code coverage.

    2) URL Routing is avaliable for WinForms. I use it myself.

    3) Built in jQuery support is in WinForms as well.

    4) Mobility support - they both use dection schemas for mobility - they are just different.

    MVC is great and I support its use but just be careful not to assume everything is black-n-white. There are cases in which use of one or the other can be argued and there is alot of overlap scenarios. I would argue knowing both approaches, their pros and cons, and choosing accordingly.

    ReplyDelete
  3. I agree with most of your arguments, but #5 seems the weakest to me. Downloading jQuery doesn't take much effort. Or you could just use the Google AJAX Libraries to include jQuery in your project. Either way, the fact that jQuery is baked into a standard ASP.NET MVC project isn't much of an advantage unless you have absolutely no idea what jQuery is.

    ReplyDelete
  4. @Nathan: Did you mean WebForms? ;) Anyhow, I agree with Nathan's observation. Whatever you can do with ASP.NET MVC, you can also do it with WebForms. As for the MVC (or MVP) pattern, well it's just that...a pattern. One that can be applied for WebForms solutions. For one enterprise WebForms application, we used the Smart Client Software Factory (http://code.msdn.microsoft.com/SmartClient/Wiki/View.aspx?title=Model-View-Presenter%20pattern) with the MVP pattern. You still get the core benefits of ASP.NET MVC, but with much more features out of the box provided by WebForms (viewstate, web controls, etc.). One objection I hear the most about switching to ASP.NET MVC is that not too many developers know how to write proper unit tests (mostly because the existing tools are too hard to use or not as expressive as they should be), so more often than not, developers will either choose "No, don't bother creating a unit testing project because I don't know much about it", or "Ok, create a unit test project, but please compile even though there aren't any tests". I haven't played with ASP.NET MVC, but if I'm a newcomer to .NET web development, I think I'd still prefer WebForms over it....at least until I know what ASP.NET MVC v2.0 will offer me. :)

    Keep up the great writing Maxime!

    ReplyDelete
  5. @Brian Oops! Yes, I meant WebForms. Proofreading fail on my part.

    ReplyDelete
  6. I would add to that simpler "page" lifecycle. There are no init, preinit, load etc events in the page and this makes it easier to code and persforms a lot faster than web forms.

    ReplyDelete
  7. Thanks for the comment everyone. I just want to tell everyone that I don't push MVC as being superior to MVP. MVC has it's advantage where MVP has it's own. What I like about the use of MVC in a stateless environment is that the pattern fits perfectly to those kind of environment. Controller receive a request for a specific action and decide on an action based on the result.

    @KevinPang: As for including a javascript framework already inside a project, it's more easier for someone to just "start coding" rather than "download a framework, copy it inside the right directory, add a reference inside the master page, start coding". The least amount of steps and the more people is going to use it. There is a lot of people that would just write their own javascript implementation because at first it was just "a small piece of code". When the javascript requirements grows... it become a beast that needs to be translated in an appropriate javascript framework. Having a framework on-hand allows less mistakes like this.

    @Bart: Yes! Simpler life cycle is definitely something we should all like! I forgot it in my post but it's more easier to understand that what you send to the browser is what they get instead of flipping switch on the server side until the view gets rendered properly. Let the view handle itself and let the controller give the data.

    ReplyDelete
  8. I've used MVC, like MVP better - gives me many more options. Routing is available to webforms, MVP and MVC - not specific. The *only* thing I personnally see that MVC gives the community is a framework that mimics that which has been used by Java/Open source frameworks. Not a bad thing, but certainly no reason to run screaming from MVP or Webforms.

    My ideal is WCSF with Silverlight as a front end, easily swapped out with Webforms and/or AJAX. Can't beat the speed to completion and the structure. IMO

    jQuery is probably the best thing to come to web development ever - standardizes manipulation of the DOM, which, without Silverlight or Flash, is key to web programming.

    ReplyDelete
  9. Nice write-up... however I too would not agree with #5. jQuery can just as easily be used in Web Forms.

    So far my experience with MVC on two large scale web applications has been positive. Looking forward to V2 with more baked in control and helper goodness. For the time being, MVC Futures provides a lot of that.

    ReplyDelete
  10. Don't get me wrong, I'm a big fan of MVC I just don't like posts like this. I feel like I should be going through each of your points and refuting it.

    I'll hold myself back and just have a gentle dig at point #2.

    2. MVC certainly isn't perfect control of urls. Sure it's a nicer default in most situations but it simply can't cover them all.

    Taking your example of
    http://localhost/Product/Detail/23213

    That's not exactly a particularly user friendly url in my opinon.

    Wouldn't the following be a much better url? (provided it's relevant to the page being displayed)

    http://localhost/Computers/CPU/Intel/Intel-Xeon-3GHZ

    Why are we still stronly coupling the url to the code it's running?

    Just because the above url should use the product controller and another (http://localhost/Computers/CPU/Intel/) would use the category controller doesn't mean it needs to be specified in the url.

    ReplyDelete
  11. MVC is better for testability. When you create the project, VS creates tests for you.
    And we've done an experiment with Isolator to make these tests even shorter.(http://blog.typemock.com/2009/04/writing-shorter-tests-don-build-tree.html ). Use any mocking framework (disclaimer I work at Typemock), but don't write all the mock stuff by hand.

    ReplyDelete

Please try to keep comments relevant to the topic. All comments after 1 month will be moderated.