Tuesday, March 22, 2011

ASP.NET Web Forms vs. ASP.NET MVC

So it has been a few years now since Microsoft introduced the ASP.NET MVC Framework which is Microsoft's implementation of the MVC Architecture for ASP.NET. No the MVC (Model-View-Controller) architecture is not a new concept; just Microsoft's implementation of it in the .NET Framework. There has been a lot of buzz around whether to continue to use ASP.NET web forms which have been around since 2001, or to go with this "hot" new technology in ASP.NET MVC... or something else! There is no 'Silver-Bullet' answer to this, and with most situations, 'it depends'.

Oh I know, you might have "Googled" the exact phrase of this blog post and were hoping to get some answer to exactly which one is better. Nope. I just want to highlight a few of the strengths and weaknesses of both from an abstract point of view, and briefly mention some other alternatives too.

To begin, I am going to repeat a stat that Andrew Duthie (Twitter handle: @devhammer) brought up on this topic at an ASP.NET Firestarter event in Orlando last December. He showed a stat that somewhere in the range of 80%+ dev shops were still using ASP.NET web forms for their bread and butter applications, and that ASP.NET web forms were not going away! Anyone trying to spread a rumor like that needs to check with the folks direct from Redmond 1st, because it simply isn't true. To this end, folks shouldn't feel like they missed the last train to MVC euphoria because everyone hasn't boarded yet. I am not building up an article against MVC; I just want to point out that it is a misnomer that ASP.NET MVC has completely replaced an outdated web forms architecture that some may speak convincingly of on forums and blogs.

So maybe you are leading a team of developers and are looking to decide the pros and cons of MVC, or maybe you are about to build a site for a friend/family member as fast as possible, or involved in a large scale enterprise application that will be web based. Whatever the scenario, you want to know the details of which architecture to choose. After all it will be quite difficult to change between the two once the code begins to flow. Making the right decision up front is important in any of these scenarios no matter how small or large the project.

Let's 1st speak to the advantages of the MVC framework. 1st and foremost in my book is the Architecture itself: M-V-C. It is going to be tough to break this model and rearrange how the application is built. Having your or your team's hand forced into a stable and mature architecture like MVC is a good thing. Raise your hand (like anyone can see...) if you have ever seen or maybe written one of those spaghetti sandwich ASP.NET web forms application that has raw SQL right behind "btnSave_Click()". Blah! Awful nasty, all code-behind the forms, non-scalable mess of an application. So 'point' to MVC for guiding developers to a decent architecture. You can adhere to several good architectures using ASP.NET, but it is up to the developer or team of developers to be disciplined enough to stick to the architecture and not lay back on a fat UI layer. Separation of concerns is a key Object Oriented Concept and a real winner for the MVC architecture. Each layer has its own responsibility, and placing the proper code in its responsible layer will make for a much better code base to scale, maintain, inherit, etc.

Next ASP.NET MVC allows the developer to have "Full Control" over the rendered HTML. For now I am going to leave this as an advantage for MVC, but caution that not everyone fully understands what this means, and it might not be advantageous for a vast majority of applications not needing this type of control. Let me elaborate a bit; that wonderful winter of 2001 when many of our lives took a turn for the better as Scott Guthrie (Twitter handle: @scottgu) came up with what is ASP.NET web forms, and decided while sipping hot cocoa that if you drug a label onto a web form, it would get rendered as a DIV tag. He made this decision (or Microsoft) and not you. You pick the ASP.NET server controls you want to drag onto a web form, but don't have control over what HTML elements actually get rendered on the client as a result. You just know that when a Gridview is dragged onto a form, it will be displayed on the client. You don't know (or need to in many situations) that it might be a series of DIVs and Input HTML controls. This abstraction is actually an advantage for ASP.NET web forms. For many web applications built, we have relied on this drag and drop capability, and trusted the final output that will be rendered to ASP.NET. However, if you have ever found the way the ASP.NET sever controls get rendered is not exactly how you want or need it, then MVC is a better choice as it will allow you to have control over the final rendering. If you do not have any main issues with how ASP.NET web form server controls get rendered in your applications, then this might not be an "advantage" that you can sell to your tech manager or team when trying to build the next project using MVC.

Another advantage of using ASP.NET MVC that ties back into the individual layers is testability, specifically unit testing. Because the application is loosely coupled with code in its separate layers, the ability to create unit tests increases greatly. The event based ASP.NET pages that rely on things like Session, Context, Response, etc are quite difficult to effectively test because of the inability to isolate specific page functionality due to its nature of being spread out and external dependencies as well. MVC improves on this greatly, and is architected to be testable. 'Point' MVC.

So let's examine ASP.NET web forms for a minute. As I mentioned they were born sometime in late 2001, so maturity and a rich tool set (both from Microsoft and 3rd party) is a big advantage. These "tools", or ASP.NET server controls make up a style of development referred to often when speaking of ASP.NET web forms called RAD or Rapid Application Development. "Hey I can drag a few ASP.NET text boxes, some labels, this Gridview thingy, press publish, and WHAT??!! I have a website!" Now that website might be junk, but hey its done already. On to the next project, right? Well not quite. 'Fast', especially in our field doesn't mean better. That site might be done, but as eluded to prior, its design is junk and it will not maintain or scale well. But what if you know the scope is a single, simple page? Well then a tool like web forms is probably perfect, and MVC might be overkill if speed of development is of the essence. Don't be fooled, web forms + data binding, etc. will be faster to generate just based on the drag-and-drop + wizardry capabilities. Just don't have a code review and everything will be fine! So the RAD capabilities of ASP.NET web forms can be a double edged sword. A quality ASP.NET web forms with a pre-determined architecture (3-layer, Domain Driven Design, MVP, etc.) that uses developers with discipline to adhere to it, is a much better choice when creating ASP.NET web form applications.

Along these lines is another advantage with web forms and that is 'Experience'; specifically in relation to a developer's experience with the technology. Again with web forms being a mature technology going on 10 years, there is a solid developer core with ample experience. If you are leading a team of 8-10 developers, you are the only one with MVC experience, and everyone else knows web forms, then this needs to play into your decision of which technology to use. Are you prepared to take the financial impact of formal MVC training through remote seminars, current books, or on-sight training? Can you afford the 1-3 month setback while the team gets up to speed on ASP.NET MVC to say a beginner/intermediate level? If these are not an issue, and the advantages of ASP.NET MVC mentioned previously are present, then it may be the better choice regardless of the upfront cost in time, money, etc. If however, you need to begin writing code immediately with a team of web form rich experience developers and are under a tight deadline, then maybe holding off on using MVC is the better decision. In the end you need to weigh the factors to make the best decision.

There are some other disadvantages to the web forms technology that I will mention briefly here as well. The web form's postback model uses client side generated '_doPostBack()' events for each server callback. If JavaScript is disabled this will cause several problems for the web forms application. It is also difficult to manipulate manually if writing your own client side scripts. MVC improves on this using REST based URLs. The next disadvantage with web forms is ViewState. Referring back to my comments about poorly designed web form applications, a bloated ViewState can cause pages to be larger and slower than they need to be. ViewState stores a base64 encoded string with information about controls state to persist postbacks and to help combat the stateless nature of the web. This however becomes a disadvantage for web forms when abused.

Now let's throw a cog into the wheel and add in another choice for web development in the .NET realm: Silverlight. Oh yeah, and honestly my favorite when it comes to rich UI content. However, you still need a hosting application and Silverlight can be integrated into either ASP.NET web forms or ASP.NET MVC applications. And I don't want to confuse anyone either because Silverlight is not an entire 'web' Framework onto its own and only works alone as individual controls. The Silverlight controls integrate into a web forms or MVC application as just another control and can co-exist with controls of either technology. However, since Silverlight can't invoke the controller class in MVC, or directly postback to the server when using web forms, you will need to use services (WCF) to accomplish this task. Anyone using Silverlight previously knows that WCF services can bridge the gap between the Silverlight control and the server.

Decisions, decisions, which technology to pick? There is a lot to weigh when it comes to these two technologies: ASP.NET web forms or ASP.NET MVC. Are you trying to draw a line in the sand and say, "Only MVC web apps from here on out!!" Personally I would not do that, because it wasn't like 10 years ago when we moved from classic ASP to ASP.NET and were able to be that bold. Now ASP.NET MVC has to be looked at as another tool (a very powerful and cool one) in the proverbial toolbox. There will be a time when MVC is the proper decision, and a time when web forms is the proper one. I strongly urge those picking web forms to at a minimum not fall into the trap of bad or poorly architected code, and be disciplined to use an architecture that is more scalable and maintainable (check my review of the book Professional ASP.NET Design Patterns). And lastly and maybe most importantly, be a 'realist' and not a 'purist' when making this decision. Do what is best and right, and not just which one theoretically is better in argument. This will help you decide. Either way its great to be a .NET developer with such a plethora of technologies to choose from.

Wednesday, March 9, 2011

How To: Encode a JavaScript string in .NET To Escape Characters (i.e. Single Quotes) Automatically

There is a handy new Utility method new to the .NET Framework 4.0 found in the System.Web.HttpUtility namepsace called HttpUtility.JavaScriptStringEncode. It allows you the developer to create any string needed and URL encodes it to be usable by JavaScript.

Ever tried making a Utility method to create a script to be registered with the page in ASP.NET that will popup a JS alert box and takes a message? Ever see what happens when you try and place a single quote in the value like "The value 'x' is not allowed"? The JS will error out on the page with a " Expected ')' " type error message. If you use the utility mentioned above, the encoding is done for you and injects any needed escape characters. The line of code below shows how this might be done in .NET code:

Dim Message As String = "The value 'x' is not allowed"
'URL Encode the message prior to registering with the page
Dim JsAlert As String = "alert('""" & HttpUtility.JavaScriptStringEncode(Message) & """');"
ClientScript.RegisterStartupScript(Page.GetType(), "AlertJsFunction", JsAlert)