Windows Phone 7 Developer Launch - Learn More
kick it on DotNetKicks.com   Shout it  

ASP.NET MVC: An Application Platform

The MVC / WebForms Debate

Yesterday I wrote about the stored procedure/dynamic sql debate - I must be feeling a bit argumentative lately, because today I was reading Tony Lombardo's post on WebForms versus MVC. I don't know Tony, I haven't read any of his other posts or met him in any forum so I don't hold anything against him. I'd be a hypocrite if I disagreed that you need to weigh the pros/cons and make an informed decision. I just made the same argument myself. However, at the end of his post he said this:

“The best advice I've seen so far is that WebForms is the platform of choice for building web applications, where MVC is more suited to building web sites.  This is still a bit abstract since there's no clear definition of web applications, but I think it's safe to say that if you're building a web version of a win client application, you're building a web application.  If you have a ‘grid' in your page for purposes above that of just layout, you're building a web application.”

It's true MVC is very attractive for “web sites” when you consider how nicely url routing helps you build an SEO friendly site that also adheres to RESTful principals. However, this is only superficial in that these are features that stand out when you look at an MVC site. These were certainly goals of the MVC team, but if that's all you see in MVC then you're judging the book by it's cover.

MVC as an Application Platform

I agree with your argument to use the best tool for the job. This is always the case in software development and loosing site of this is just going to bite you in the end. However, I believe that as future versions continue to be released WebForms will continue to loose ground because MVC will cover more and more scenarios where WebForms holds an advantage. I disagree with the recommendation that Application == WebForms, WebSite == MVC.

MVC is an application platform from the ground up. There are many reasons why, here are some that matter to me:

Model Binding

When WebForms was first released I was so excited that I didn't have to use Request.Form[] and Request.QueryString[] (or just plain Request[]) to get access to my form data. I could look at a TextBox or better yet a DropDownList and get not only the value submitted via POST but I could inspect additional properties like SelectedItem.Text. It was a much richer model than classic ASP.

What this new model didn't do for me was return primitive types (unless I built my own custom controls or purchased a 3rd party control library). I still had to parse the strings to primitive types, but at least validation allowed me to safely do so without using TryParse().

I have been using MVC since Preview 1 (Nov 2007) and I have found that it gets out of my way. I get strongly typed binding both in my view and when responding to any request. I no longer have to spend time parsing strings into primitive types then hydrating an object by hand. Instead I just have to do this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
 
namespace MyApp.Web.Controllers
{
    public class MyObject {
        DateTime Date { get; set; }
        Int64 Integer { get; set; }
        String Text { get; set; }
    }
 
    public class Default1Controller : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Index() {
            return View();
        }
 
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(MyObject model) {
 
            // save my model
            Repository.Save(model);
 
            return View();
        }
    }
}

I think that speaks for itself.

RAD Without Drag-n-Drop

It's no secret you get no DnD from MVC. But here's what you do (or will) get:

  • Scaffolding – at the moment this is a bit of a stretch to say MVC gives you scaffolding. It doesn't support DynamicData yet (it's in the pipeline), but on a per View basis you can have an entire page built for you (List, Create, Edit, Detials) with a strongly typed model by selecting the type of page you want and the type of your model.

    image 

  • Easy HttpHandlers – need to return an image or file other an an HTML response? The WebForms way is usually to create a Generic Handler (a class inheriting from IHttpHandler). You can do it with System.Web.UI.Page as well, but the point is that you create the handler create your content, set your Http headers and then write to the response stream. With MVC you simply return from an action a result type that corresponds to your content/type or use File and specify the mime type:
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Ajax;
     
    namespace MyApp.Web.Controllers
    {
        public class Default1Controller : Controller
        {
            //
            // GET: /Default1/
     
            public FileResult SomeFile()
            {
                return File("/Path/To/File.ext", "content/type");
            }
     
            public JsonResult JavaScriptObject() {
                return Json(new { 
                    Property1 = "something", 
                    Propety2 = DateTime.Now, 
                    Property3 = 323.00 
                });
            }
     
            public JavaScriptResult ClientScript() {
                return this.JavaScript("function message(val) { alert(val); }");
            }
     
            public PartialViewResult HtmlSnippet() {
                return PartialView("NameOfAscxControl.ascx");
            }
        }
    }
  • Lightweight Web Services – as a side effect of easy control over the mime-type of your results you can create your own lightweight web services without the need of formally creating web services via .asmx or .svc files. JsonResult allows you to make easy calls from your javascript and return a JSON resonse or use FileResult and specify application/xml as your content type and you're off and running with a working response to an ajax request to a RESTful interface.

Testability

If I'm building an application then being able to write unit tests for both my application logic and business logic is very important to the long-term life of my project. Applications are organic, they change and grow in size and complexity. Often an application will outlive the employment of the programmer(s) who wrote it. Maintaining unit tests ensure that the application continues to work as intended. This keeps things clean and maintainable, which in turn extends the life of your application longer than any other method I know of.

Control

WebForms is very closed when compared to MVC. Sure you get a lot of control/flexibility through HttpModules, HttpHandlers, Application and Page events, Server Controls. But many times I have needed to add custom logic which required a hack because I couldn't put it where I needed to most to get the cleanest or most effective solution. You can debate that if you know what you're doing then it isn't a problem and I won't let my pride get in the way of that. But in MVC I can hook in wherever I want at any level and MVC doesn't try to “protect” me from myself. I could shoot myself in the foot, but I'm also free to do what I decide is best for my application. This is something you can't fully appreciate until you experience it.

Other Concerns

WebForms Designer vs. Raw HTML

Many people site having to get their hands dirty in html and how nicely WebForms abstracts these details from them. This is strictly my own opinion and I may be biased. I started out almost 10 years ago writing HTML and classic ASP in notepad and I have never used the WebForms designer. I've tried it many times, but I find that it slows me down and very quickly looses any fidelity with the end result such that it becomes worthless to me.

Writing server controls by hand and writing raw HTML by hand are almost the same – it's all tag soup. In some cases I'd even rather write the raw HTML when you compare the two:

<asp:TextBox ID="myTextBox" runat="server" />

compared to:

<input type="textbox" id="myTextBox" />

But even there I get helpers:

<%=Html.TextBox("myTextBox")%>

Tag Soup?

On a related note: after years of WebForms we've become conditioned to believe that the classic ASP style escapes (<%= %>)are bad, bad, bad. It's mixing server code with markup. How's that different from a server control – it isn't html either, it just looks like it.

What's bad is placing logic into the page. Rob Conrey demonstrated this better than I ever could.

Conclusion

Should you evaluate the needs of your application against the benefits of WebForms vs MVC? Yes. Should you learn MVC so you know what it has to offer? Most definitely. Will you regret using MVC? I haven't and I don't believe you will. MVC is an incredible application platform and it will only get better. WebForms was developed in a relatively closed way, whereas from day one MVC was developed with extensive community involvement and feedback. It had 5 preview releases before beta and was being used in production environments all along the way. The MVC team developed this so that it works and it works well. Give it a spin, you won't regret it.

Tags: , ,

kick it on DotNetKicks.com   Shout it  

Feedback

# 

Gravatar Absolutely OK with that analysis... In other terms, choosing between Webforms and MVC is just a question of architecture !

Developers who really care about unit test often choose MVC...

And for those who don't understand where the progress is, when you loose the power of asp.net components, just think about jQuery... :) 7/22/2009 6:24 AM | noreply@blogger.com (Jérôme A.)

# re: ASP.NET MVC: An Application Platform

Gravatar Nice post. You can also find the comparison here
www.techbubbles.com/.../aspnet-mvc-and-web-forms/
9/6/2009 3:56 PM | Kalyan

Comments have been closed on this topic.
 

 

Copyright © Mark J. Miller